简体   繁体   中英

What are the cases in which arrays decay to pointers?

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

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.

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] . However, what happens here is actually:

  • a is converted to a pointer.
  • 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.)

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. The operand of _Alignof is always a type; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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