简体   繁体   English

数组衰减到指针的情况是什么?

[英]What are the cases in which arrays decay to pointers?

我只知道一个例子,当数组传递给一个函数时,它们会衰变成一个指针。任何人都可以详细说明数组衰减到指针的所有情况。

C 2011 6.3.2.1 3: C 2011 6.3.2.1 3:

Except when it is the operand of the sizeof 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. 除非它是sizeof运算符,...或一元运算符的操作数,或者是用于初始化数组的字符串文字,否则将类型为“array of type ”的表达式转换为类型为“指向类型的指针”的表达式“它指向数组对象的初始元素,而不是左值。

In other words, arrays usually decay to pointers. 换句话说,数组通常会衰减为指针。 The standard lists the cases when they do not . 标准列出了他们不这样做的情况。

One might think that arrays act as arrays when you use them with subscripts, such as a[3] . 有人可能会认为,当您使用下标时,数组就会充当数组,例如a[3] However, what happens here is actually: 但是,这里发生的事实是:

  • a is converted to a pointer. a转换为指针。
  • The subscript operator acts on the pointer and the subscript to produce an lvalue designating the object. 下标运算符作用于指针和下标,以产生指定对象的左值。 (In particular, a[3] is evaluated as *((a)+(3)) . That is, a is converted to a pointer, 3 is added to the pointer, and the ***** operator is applied.) (特别是, a[3]被评估为*((a)+(3)) 。也就是说, a被转换为指针,3被添加到指针,并且应用了*****运算符。 )

Note: The C 2011 text includes “the _Alignof operator.” This was corrected in the C 2018 version of the standard, and I have elided it from the quote above. 注意:C 2011文本包含“ _Alignof运算符”。这在标准的C 2018版本中得到了纠正,我从上面的引用中删除了它。 The operand of _Alignof is always a type; _Alignof的操作数始终是一种类型; you cannot actually apply it to an object. 你实际上不能将它应用于一个对象。 So it was a mistake for the C 2011 standard to include it in 6.3.2.1 3. 因此,C 2011标准将其纳入6.3.2.1 3是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM