Sriram Jayaraman Sriram Jayaraman - 4 months ago 11
C Question

Does increment in pointer not same as that of integer?

Consider the code below:

void increment(int* a)
{
printf("%d\n",a);
*a=*a+1;
}
int main()
{
int a=10;
int* p=&a;
increment(&a);
printf("%d",a);
return 0;
}


This increments a to be 11 but this :

void increment(int* a)
{
printf("%d\n",a);
*a++;
}
int main()
{
int a=10;
int* p=&a;
increment(&a);
printf("%d",a);
return 0;
}


The above code generates value as 10.

Is the pointer arithmetic not like integer arithmetic or am I missing something here??

Answer

You are missing operator priorities. The (*a)++; is something totally different from *a++. The first one increments value at address a, second one post increment a and gets value at the original address.