我对此有点困惑。 在我的系统上,如果我这样做:
printf("%d", sizeof(int*));
这只会产生 4。现在,sizeof(int)
也会发生同样的情况。结论:如果整数和指针都是 4 个字节,则指针可以安全地“转换”为 int
(即它指向的内存可以存储在 int 中)。但是,如果我这样做:
int* x;
printf("%p", x);
返回的十六进制地址远远超出了 int 范围,因此任何将值存储在 int 中的尝试显然都会失败。
这怎么可能?如果指针占用4个字节的内存,它怎么能存储超过232?
编辑: 根据一些用户的建议,我发布了代码和输出:
#include <stdio.h>
int main()
{
printf ("%d\n", sizeof(int));
printf ("%d\n", sizeof(int*));
int *x;
printf ("%d\n", sizeof(x));
printf ("%p\n", x);
}
输出:
4
4
4
0xb7778000
最佳答案
C11,6.3.2.3,第 5 段和第 6 段:
An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
因此,转换是允许的,但结果是实现定义的(如果结果不能存储在整数类型中,则结果是未定义的)。 (“先前指定”指的是NULL。)
关于指针打印大于 4 字节数据可以表示的内容的打印语句,这是不正确的,因为 0xb7778000
在 32 位整数类型的范围内。
关于c - 指针如何存储在内存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17686484/