y的价值应该是什么?为什么?
int x[] = { 1, 4, 8, 5, 1, 4 };
int *ptr, y;
ptr = x + 4;
y = ptr - x;
Run Code Online (Sandbox Code Playgroud)
我认为y应该是4*sizeof(int),但它给出了4.为什么?
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);
Run Code Online (Sandbox Code Playgroud)
输出:
x[0] x[1] x[2] x[3] x[4] x[5]
0xbf871d20, 0xbf871d24, 0xbf871d28, 0xbf871d2c, 0xbf871d30, 0xbf871d34
ptr x
0xbf871d30 - 0xbf871d20
4
Run Code Online (Sandbox Code Playgroud)
所以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;
Run Code Online (Sandbox Code Playgroud)
现在y将给你0x10(十六进制)或16(十进制)
它应该是指向起始x地址的地址与x的第4个元素的地址=> 4 之间的int数.
从c99标准:
6.5.6加法运算符
9 /当减去两个指针时,两个指针都指向同一个数组对象的元素,或者指向数组对象的最后一个元素的元素; 结果是两个数组元素的下标的差异.
要了解更多信息,请尝试搜索指针算法.