Array Decaying
Learn about the important mechanism of array decaying.
We'll cover the following...
Introduction
We discovered that arr just like &arr[0] is a pointer to the first element inside the array.
See the following code, where we print their addresses. It’s the same code we used in previous lessons:
Here’s a possible output:
Address of arr = 1865475828
Address of arr[0] = 1865475828
The two addresses are equal.
Moreover, in lines 11 12, we aren’t receiving any warnings from the compiler, which means that both arr and &arr[0] have the same type (pointer to int).
In conclusion, the array name is a pointer to the first element. This conversion happens because of array decaying, which we’ll now explore in depth.
Array decaying
Array decaying is a process in which an array loses its size information and is converted from an array of type T to a pointer to type T. The pointer points to the first element inside the array.
We say that the array decays into a pointer.
This process happens in expressions involving arrays, with the following exceptions:
- The
sizeofoperator - The address of the
&operator - With string literals, when they’re used to initialize a
chararray. We’ll discuss this at a later point.