我在理解 C 中的一件事时遇到问题。我在“ANSI C”中读到像 a[n]
这样的语句,其中 a
是数组实际上等同于 *(a+n)
。所以这是我编写的一小段代码来检查:
#include <stdio.h>
int main(void)
{
int a[10] = {0,1,2,3,4,5,6,7,8,9};
int *p = a;
printf("sizeof a: %d\n", sizeof(a));
printf("sizeof p: %d\n", sizeof(p));
return 0;
}
执行代码后程序输出:
sizeof a: 40
sizeof p: 8
我不明白 - 我刚刚做了什么? a
和 p
有何不同的对象? (根据sizeof函数的输出判断)
最佳答案
根据C标准(6.5.3.4 The sizeof and alignof operators)
2 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
所以定义为 10 个整数数组的对象 a
占用大小为 40 字节的内存范围,因为它的每个元素依次具有 4 字节的大小(即在您的环境中 sizeof( int ) 等于 4).
int a[10] = {0,1,2,3,4,5,6,7,8,9};
对象 p
被定义为一个指针,并由数组 a
的第一个元素的地址初始化
int *p = a;
在你编译的环境下,指针的程序大小等于8字节。
可以考虑声明
int *p = a;
也喜欢
int *p = &a[0];
关于c - a[n] 真的可以与 *(a+n) 互换吗 - 为什么 sizeof 返回两个不同的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29658067/