The memory addresses of elements of the same array are always sequential. those. if the memory address is myarray [0]:
0x4000000
then the memory address myarray [2] will definitely be
0x4000002
So when you store the address arr in ptr1 , assume that it is x , and then when you make the address ptr2 , three units higher than ptr1, it will be x + 3 . So when you subtract ptr1 from ptr2, the answer is as follows:
( x +3) - x = 3
Hence the answer.
In the second expression of printf (), if you want it to display the same result as above (3), you need to convert the pointer to int , not int* .
char *myvar;
So in your case:
printf ("(int)ptr2 - (int) ptr1 = %d", (int)ptr2 - (int)ptr1);
source share