73
votes

I have seen in many posts that "in most of the cases array names decay into pointers".
Can I know in what cases/expressions the array name doesn't decay into a pointer to its first elements?

1
More context is required: Are you working in a specific language? Do you have an example?abiessu
consider C language. And i'm looking for an example where array names doesn't decay into pointer.nj-ath
@TheJoker I given here an answer in which I show this casesGrijesh Chauhan
Re H2Co3's second point, i.e. with sizeof, I'm reading Head First C, and it first illustrates pointer decay using sizeof(msg) inside a function where msg was passed in as an argument. They had a little box explaining that an array variable decays to a pointer when it's passed into a function as an argument (paraphrasing) so you get 4 or 8 (bytes), not array size. I got confused because in the next chapter on the string library, they introduce strlen() and use it the same way they'd used sizeof(). I came here to straighten my head out and now you twisted it up a little more. :Ppunstress
This answer has all the exceptions with examples.legends2k

1 Answers

63
votes

Sure.

In C99 there are three fundamental cases, namely:

  1. when it's the argument of the & (address-of) operator.

  2. when it's the argument of the sizeof operator.

  3. When it's a string literal of type char [N + 1] or a wide string literal of type wchar_t [N + 1] (N is the length of the string) which is used to initialize an array, as in char str[] = "foo"; or wchar_t wstr[] = L"foo";.

Furthermore, in C11, the newly introduced alignof operator doesn't let its array argument decay into a pointer either.

In C++, there are additional rules, for example, when it's passed by reference.