Basically when I run this as it is it prints 1 and 2. First of all, ptr2 - ptr should be 4 as I see the pointers pointing to something like this, where each | | represents one byte:
|0|0|0|0| 0|0|1|0|
ptr..........ptr2
When we subtract pointers we subtract the addresses they point to, right? So I would expect 4 to be printed and then 2, since the memory has been allocated continuously.
Of course this is not the actual output. So where is my thinking incorrect?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *ptr;
ptr = (int *)malloc(2*sizeof(int));
int *ptr2;
ptr2 = &ptr[1];
printf("%d\n", ptr2 - ptr);
ptr[1] = 2;
printf("%d", ptr2[0]);
free(ptr);
return 0;
}