I think y should be 4*sizeof(int)
好主意,你猜怎么着?它正在提供4*sizeof(int),但您看的不对。 ;)
当你玩指针时,你在看地址,所以让我们看看一些地址
int x[] = { 1, 4, 8, 5, 1, 4 };
//Just for fun, what is the address of each element in the array?
printf("%#x, %#x, %#x, %#x, %#x, %#x\n", x+0, x+1, x+2, x+3, x+4, x+5);
ptr = x + 4;
printf("%#x - %#x\n", ptr, x); // Give us the address of ptr in hex
// and give us the address of x
y = ptr - x;
printf("%d\n", y);
输出:
x[0] x[1] x[2] x[3] x[4] x[5]
0xbf871d20, 0xbf871d24, 0xbf871d28, 0xbf871d2c, 0xbf871d30, 0xbf871d34
ptr x
0xbf871d30 - 0xbf871d20
4
所以 ptr 是x+4(在你的情况下实际上是x + 4*sizeof(int) 或x+16)。我们将从x 或基地址中减去,所以实际的数学是0x30 - 0x20 = 0x10 或十进制16。
您在输出中看到4 的原因是因为编译器知道您正在对int * 执行操作,所以它为您将16 除以sizeof(int)。不错嗯?
如果您想查看实际值,您需要执行以下操作:
int one, two;
...
one = (int)ptr; //get the addresses, ignore the "type" of the pointer
two = (int)x;
y = one - two;
现在y 会给你 0x10(hex) 或 16(dec)