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?
-
2More context is required: Are you working in a specific language? Do you have an example?abiessu– abiessu2013-07-19 18:23:45 +00:00Commented Jul 19, 2013 at 18:23
-
consider C language. And i'm looking for an example where array names doesn't decay into pointer.nj-ath– nj-ath2013-07-19 18:25:42 +00:00Commented Jul 19, 2013 at 18:25
-
1@TheJoker I given here an answer in which I show this casesGrijesh Chauhan– Grijesh Chauhan2013-07-19 18:57:28 +00:00Commented Jul 19, 2013 at 18:57
-
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– punstress2013-08-06 00:36:34 +00:00Commented Aug 6, 2013 at 0:36
-
This answer has all the exceptions with examples.legends2k– legends2k2014-07-09 08:27:53 +00:00Commented Jul 9, 2014 at 8:27
1 Answer
Sure.
In C99 there are three fundamental cases, namely:
when it's the argument of the
&(address-of) operator.when it's the argument of the
sizeofoperator.When it's a string literal of type
char [N + 1]or a wide string literal of typewchar_t [N + 1](Nis the length of the string) which is used to initialize an array, as inchar str[] = "foo";orwchar_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.
16 Comments
char. The right side of an array initialization statement doesn't even take an expression, so it doesn't make sense as an answer to this question.