我有以下代码:
main() {
int array[5] = {3,6,9,-8,1};
printf("the size of the array is %d\n", sizeof(array));
printf("the address of array is %p\n", array);
printf("the address of array is %p\n", &array);
int * x = array;
printf("the address of x is %p\n", x);
printf("the size of x is %d\n", sizeof(x));
}
输出结果为
the size of the array is 20
the address of array is 0x7fff02309560
the address of array is 0x7fff02309560
the address of x is 0x7fff02309560
the size of x is 8
我知道变量array
会被视为指向数组第一个元素的指针,因此我理解x的大小为8。但我不知道数组的大小为什么是20。在64位机器上不应该是8吗?
另外程序如何知道它的大小是20呢?据我所知,在C语言中它不存储元素的数量。为什么sizeof(array)
和sizeof(x)
不同?我查阅了关于数组衰减的帖子,但对这个问题没有头绪。
sizeof
的结果。这是编译器的工作,需要它来完成。 - Jonathan Lefflersizeof
不是一个函数,而是一个编译时运算符。只有编译器需要知道答案,因此信息不被“存储”在程序中也没有关系。 - Euro Micelli