Pointer/Address difference [duplicate]

痞子三分冷 提交于 2019-12-17 06:53:06

问题


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

回答1:


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.




回答2:


As others have said, the result you get is in a multiple of the size of the type the pointers are pointing to. Cast them to be char pointers and the result you get will be in terms of bytes. Also, you should use the ptrdiff_t type, so that on systems with 64-bit pointers the type should be large enough to hold the result.

ptrdiff_t c = (char*)p - (char*)q;

Also note that taking the difference of the addresses of two values that aren't in the same array is undefined in the standard, but does work on about every system.




回答3:


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.



来源:https://stackoverflow.com/questions/9855482/pointer-address-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!