0

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;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
Stormlight
  • 161
  • 3
  • 10

1 Answers1

2

When you subtract two pointers, the result is not difference between the numerical values but the difference in the number of elements.

Since ptr points to the first element of an array and ptr2 points to the second element, there is a one element difference between the two, and that is the result.

Section 6.5.6 of the C standard regarding Additive Operators states the following:

9 When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

If you want to see the byte difference between the addresses, you can cast the pointers to char *:

char *p1 = (char *)ptr;
char *p2 = (char *)ptr2;
printf("%td\n", p2 - p1);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • But I am allocating memory worth 8 bytes. ptr2 should point to index 4, right? There is a 4 byte difference between index 4 and index 0. – Stormlight Mar 27 '18 at 19:48
  • 1
    @CodeChef123 The byte index is irrelevant. Even though the pointers may in fact be 4 bytes apart, if an `int` is 4 bytes in size that means that the pointers are 1 `int` apart, which is what the result is. If you had casted those pointers to `char *`, then you would see a different results because a `char` is a different size from an `int`. – dbush Mar 27 '18 at 19:51