c - a[n] 真的可以与 *(a+n) 互换吗 - 为什么 sizeof 返回两个不同的答案?

标签 c arrays pointers

我在理解 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

我不明白 - 我刚刚做了什么? ap 有何不同的对象? (根据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/

相关文章:

c++ - 识别回文字符数组的递归函数

c - C 中的指针比较。它们是有符号的还是无符号的?

C:指向指定长度类型的指针

获取IP地址的C代码

C:访问 char 数组中连续的 12 位序列

c - 如何释放单链表中的内存

php - Friend_array 删除

java - 数组中的多种类型用于初始化

c++ - 分配 std::shared_ptr

c - 重新实现库函数作为其他语言的实践