Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

No such thing as double decay in C?

I’ve reading posts such as this one Doesn’t a 2D array decay to pointer to pointer as well as similar ones but I still don’t see the big picture.

Take the following code as an example:

int a[2][2] = {{1,2},{3,4}};
int *p;
p = *a; // This works even without derefrencing a
printf("%d\n", *p); // output is 1

*a gives a pointer to the first element of a which is an array of size 2 and it is assigned to p. Firstly, how does this not raise a warning? p is a pointer to an int and *a is an array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

We then print *p which outputs 1. How does this make sense without the array decaying twice? *p will be {1,2} so doesn’t it make sense that *p decays into a pointer to the first element of the subarray?

But, in C this isn’t possible. So what’s going on?

>Solution :

The simple answer is, any time an expression with array type appears in a rvalue context, it "decays" into a pointer — it is implicitly converted into a pointer to the array’s 0th element.

So what does this mean for the expression p = *a?

Well, here a has array type (int [2][2]) so it is converted into a pointer (an int (*)[2]). This pointer is then dereferenced (*a), which gives another array (an int [2]), so that also is converted into a pointer, this time an int *.

So there are two separate decay conversions in this statement (in some sense a "double decay"), but they are on two different array types and array values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading