[英]Why is (int)((int *)0 + 4) == 16?
I have tested this, k
is 16, but why? 我已经测试过,
k
为16,但是为什么呢?
int main(int argc, char **argv) {
int k = (int)((int *)0 + 4);
printf("%d", k);
return 0;
}
Important note: Pointer arithmetic on a pointer that does not point to an array is undefined behavior. 重要说明:未指向数组的指针的指针算术是未定义的行为。 You can get 16, but you can also get a crash, for example, if the implementation chooses to produce a trap representation for the result.
例如,如果实现选择为结果生成陷阱表示,则可以得到16,但也可能导致崩溃。
This is pointer arithmetic: when you add a number x
to a pointer to T
, numeric value that corresponds to the pointer is increased by x * sizeof(T)
. 这是指针算法:将数字
x
添加到T
的指针时,对应于该指针的数值增加x * sizeof(T)
。
In your case, the numeric value of the pointer is zero, x
is 4, and sizeof(int)
is also 4. 4*4
yields 16. 在您的情况下,指针的数值为零,
x
为4, sizeof(int)
也为4。4 4*4
得出16。
Pointer arithmetic in C use the type's size as an unit; C语言中的指针算术使用类型的大小作为单位。 adding 1 to int* will make it advance by 4 (assuming int is 32bit).
将1加到int *会使它前进4(假设int是32位)。
EDIT: pointer arithmetic on invalid pointers (including NULL) is undefined behavior. 编辑:无效指针(包括NULL)上的指针算术是未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.