Search code examples
cpointerssubtraction

Subtracting two pointers giving unexpected result


#include <stdio.h>

int main() {
    int *p = 100;
    int *q = 92;
    printf("%d\n", p - q);  //prints 2
}

Shouldn't the output of above program be 8?

Instead I get 2.


Solution

  • Undefined behavior aside, this is the behavior that you get with pointer arithmetic: when it is legal to subtract pointers, their difference represents the number of data items between the pointers. In case of int which on your system uses four bytes per int, the difference between pointers that are eight-bytes apart is (8 / 4), which works out to 2.

    Here is a version that has no undefined behavior:

    int data[10];
    int *p = &data[2];
    int *q = &data[0];
    // The difference between two pointers computed as pointer difference
    ptrdiff_t pdiff = p - q;
    intptr_t ip = (intptr_t)((void*)p);
    intptr_t iq = (intptr_t)((void*)q);
    // The difference between two pointers computed as integer difference
    int idiff = ip - iq;
    printf("%td %d\n", pdiff, idiff);
    

    Demo.