gpt4 book ai didi

c - 为什么我可以使用数组而不是结构体作为 C 中的标量?

转载 作者:行者123 更新时间:2023-11-30 20:56:33 25 4
gpt4 key购买 nike

在 C 中,数组变量可以用作标量。例如:

char A[5];
if(A) printf("True\n");

将打印 True。鉴于:

struct S { int i; } s;
if(s) printf("True\n");

实际上将无法编译,并给出错误:

错误:在需要标量的情况下使用了结构类型值

这是为什么呢?

为什么数组变量可以用作指针而不是结构体变量?

谢谢。

编辑:也许这是重新表述问题的更好方法为什么 C 赋予 A (标量)含义而不是 S?

编辑:我的问题本质上更具哲学性。我试图理解为什么 C 是这样设计的。为什么数组的作用类似于指针,而结构则不然。它们都代表连续的内存块。该内存的结构不同,但这为什么重要。

我对编译失败的原因不感兴趣,我理解这一点(我证明了它没有)。

最佳答案

Why can array variables be used as pointers but not structure variables?

数组名称转换为指向其第一个元素的指针。

C11:6.3,2.1:

...an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

结构并非如此。

关于c - 为什么我可以使用数组而不是结构体作为 C 中的标量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24122390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com