Pointer/Address difference

Ava picture Ava · Mar 24, 2012 · Viewed 17.8k times · Source

Why is the difference between the two addresses wrong? http://codepad.org/NGDqFWjJ

#include<stdio.h>
int main()
{
   int i = 10, j = 20;
   int *p = &i;
   int *q = &j;
   int c = p - q;
   printf("%d\n", p);
   printf("%d\n", q);
   printf("%d", c);
   return 0;
}

Output:

-1083846364
-1083846368
1

Answer

cnicutar picture cnicutar · Mar 24, 2012

First, pointer arithmetic isn't defined when performed on unrelated pointers.

Second, it makes sense. When subtracting pointers you get the number of elements between those addresses, not the number of bytes.

If you were to try that with

char *p1 = &i, *p2 = &j;

you would get a different result.


As a side note, use %p when printing pointers.