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??
The statement printf("%d\n",a);
does not print the value of the integer pointed to by a
. As written, it invokes undefined behavior.
printf("%p\n", (void*)a);
would print the value of the pointer, ie the address of the integer variable.
printf("%d\n", *a);
would print the value of the integer.
Futhermore, *a=*a+1;
is not the same as *a++;
. Due to operator precedence rules, *a++
is parsed as *(a++)
, the pointer is incremented, not the value pointed to. You could use ++*a;
as a shorthand for *a = *a + 1;
, and other variants are possible: ++a[0]
, a[0]++
, (*a)++
, but the preferred solution is:
*a += 1;