Călin Calin - 1 year ago 75
C Question

# Why does pointer subtraction in C yield an integer?

Why if I subtract from a pointer another pointer (integer pointers) without typecasting the result will be 1 and not 4 bytes (like it is when I typecast to int both pointers). Example :

``````int a , b , *p , *q;
p = &b;
q = p + 1; // q = &a;
printf("%d",q - p); // The result will be one .
printf("%d",(int)q - (int)p); // The result will be 4(bytes). The memory address of b minus The memory address of a.
``````

Why If If I subtract from a pointer another pointer (integer pointers) without typecasting the result will be 1 and not 4 bytes

That's the whole point of the data type that a pointer pointing to. It's probably easier to look at an array context like below. The point is regardless of the underlying data type (here `long` or `double`), you can use pointer arithmetic to navigate the array without caring about how exactly the size of its element is. In other words, (pointer + 1) means point the next element regardless of the type.

``````long l[] = { 10e4, 10e5, 10e6 };
long *pl = l + 1;    // point to the 2nd element in the "long" array.

double d[] = { 10e7, 10e8, 10e9 };
double *pd = d + 2;    // point to the 3rd element in the "double" array.
``````

``````int a , b , *p , *q;
The fact that `a` and `b` are declared next to each other does not mean that `a` and `b` are allocated next to each other in the memory. So `q` is pointing to the memory address next to that of `b` - but what is in that address is undefined.