I'm new to C programming and trying to understand how pointer arithmetic works. The below printf statement prints 2 when the arguments for printf is *(p+2) and 4 with for *p. Could you please explain this behaviour ?
#include <stdio.h>
#include <conio.h>
int main()
{
int arr[4] = {4,3,2,1}, *p = arr;
printf("\n%d", *(p+2));
return 0;
}
Let's re-write your program to make it a little clearer:
Now,
*(p+2)is by definition the same asp[2]. Sinceppoints to the first element ofarr, thenp[2]is the same asarr[2]which is equal to2.Similarly,
*(p)is the same as*pand sinceppoints to the first element ofarrthen*(p)is4.You probably need to re-read the section in your text book that covers pointer arithmetic.