Showing posts with label Pointers in C. Show all posts
Showing posts with label Pointers in C. Show all posts

Tuesday, March 22, 2016

Pointer Arithmetic

You are well aware about arithmetic of other variable like int, float, double etc. and you must think about whether those can be applied to a pointer variable or not. No, you can’t apply arithmetic operation like addition, subtraction, multiplications etc. between two pointer variables. The operations given below give you a Compiler Error.
int i=10;
int j=20;
int *pi = &i, *pj = &j;
int *res = *pi + *pj /* Compilation Error */
res = *pi - *pj /* Compilation Error */
res = *pi * *pj /* Compilation Error */
Only thing you can do is to increment and decrement operation to a pointer variable. This is mostly used by C programmers when dealing with arrays or strings.
char s[] = "a4academics.com";
char* ptr = s;

printf(“%s\n”,ptr);
printf(“%c\n”,*ptr);
printf(“%c\n”,*(ptr + 3));
ptr+=5;
printf(“%c\n”,ptr);
ptr--;
printf(“%c\n”,ptr);

The above gives following output:
a4academics.com
a
c
d
a

Thursday, March 17, 2016

Pointers in C

Pointers are often used to make C programming much easier and it helps programmers improve their program's efficiency. Not only that, by using the pointer's you can achieve unlimited amount of memory usage in your program, that’s cool right.

Definitions and Uses of Pointers

Pointers are the variables that hold an address of another variable of the same data type. The cool thing about the address of a variable is that, you'll then be able to go to that address and access the data stored in it. Pointers are basically used in the C in different ways. Some of them are:
  • To create dynamic and flexible data structures.
  • To pass and handle variable arguments passed to functions (Call by reference).
  • To retrieve information stored in list like arrays.

Pointer Variables

As I said earlier, pointers indicate the memory address of any kind of object i.e. It can be address of any primitive data types or structures or even functions. The variable which holds the address is called the pointer variable.