Alex Rivera | Logout

Pointer/Address difference

Asked 2012-03-24T20:47:54.533
9

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
Edit
Report

1 Answer

2

Strictly speaking, your program causes a few kinds of undefined behaviour, first due to the pointer arithmetic on unrelated pointers, and then by having mismatched format strings and arguments in your print statements. However, even if those were corrected, you'd see the same results. The reason the difference is 1 is because pointer arithmetic gives results in units of the size of the pointed to type - in your case int is a 4-byte type, so subtracting int * pointers that point 4 bytes apart yields a result of 1.

answered 2012-03-24T20:52:02.263

Your Answer