Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c - What are the cases in which arrays decay to pointers?

I know only one case when arrays passed to a function they decay into a pointer.Can anybody elaborate all the cases in which arrays decay to pointers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...