为什么C中的结构体名称不是指针?

2024-03-28

数组名称是指针,函数名称也是指针,但结构名称不是指针。我想了解这种差异背后是否存在某种逻辑推理,或者它只是 C 语言的随机语法?


数组很奇怪。他们的行为与其他类型不同。

C was derived from an earlier language named B1, which maintained a separate pointer to the first element of an array. Given the declaration

auto a[10];

你会在内存中得到类似下面的内容:

   +–––+
a: |   | ––+
   +–––+   |
    ...    |
     +–––––+
     |
     v
   +–––+
   |   | a[0]
   +–––+
   |   | a[1]
   +–––+
    ...
   +–––+
   |   | a[9]
   +–––+

数组下标运算a[i]被定义为*(a+i)- 给定存储在的起始地址a, 抵消i元素(不是字节) 来自该地址并取消引用结果。

在设计 C 时,Ritchie 希望保留 B 的数组语义,但他不想保留指向第一个元素的单独指针,因此他摆脱了它 - 相反,他创建了最终标准化的规则,如下所示:

6.3.2.1 Lvalues, arrays, and function designators
...
3     Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, 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. If the array object has register storage class, the behavior is undefined.
C 2011 Online Draft http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

当你在 C 中声明一个数组时

int a[10];

你会在记忆中得到这个:

   +---+
a: |   | a[0]
   +---+
   |   | a[1]
   +---+
    ...
   +---+
   |   | a[9]
   +---+

没有为单独的指针对象分配空间。下标运算a[i]仍然定义为*(a + i),这就是本例中的表达式a作为计算的一部分,从数组类型转换为指针类型。

这很重要 - 数组名称a 不是一个指针。相反,表达 a根据需要从数组类型转换为指针类型。

函数也有类似的规则:

4     A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator,65) or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.
65) Because this conversion does not occur, the operand of the sizeof or _Alignof operator remains a function designator and violates the constraints in 6.5.3.4.
ibid.

结构类型不像数组那样工作 - 成员不是根据基地址的数字偏移量来访问的。有一个完全不同的机制在起作用,所以struct foo表达式不会像数组表达式或函数指示符那样“衰减”为指针类型。


  1. 如果你真的感兴趣,你可以阅读 Ritchie 自己关于开发 C 的描述本文 https://www.bell-labs.com/usr/dmr/www/chist.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么C中的结构体名称不是指针? 的相关文章

随机推荐