Array Decaying
Learn about the important mechanism of array decaying.
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:
#include <stdio.h>int main(){int arr[3];printf("Address of arr = %u\n", arr);printf("Address of arr[0] = %u\n", &(arr[0]));//these two pointers are unused, we just want to check if the compiler issues any type mismatch warningsint *ptr1 = arr;int *ptr2 = &arr[0];return 0;}
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
sizeof
operator - The address of the
&
operator - With string literals, when they’re used to initialize a
char
array. We’ll discuss this at a later