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

No comments: