Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
Kuldeep Singh Avatar asked Dec 12 '22 20:12

Kuldeep Singh


1 Answers

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.

like image 125
Eric Postpischil Avatar answered Jan 17 '23 12:01

Eric Postpischil