Array decay explained
What you'll learn: Understand how C automatically treats an array name as a pointer to its first element in most situations.
The disappearing act
In C, an array is a fixed block of memory. However, arrays have a peculiar behavior: the moment you try to use an array name in an expression, it "decays" (converts) into a pointer.
Think of a large building like a library. The "array" is the entire physical structure. But if you give someone the address of the library, you aren't handing them the building; you are handing them a slip of paper pointing to the front door. In C, the array name is the building, but the compiler almost always treats it as the address of the front door.
How it works in code
When an array decays, it becomes a pointer to its first element (index 0). This is why you don't need the address-of operator (&) when assigning an array to a pointer.
#include <stdio.h>
int main() {
int numbers[3] = {10, 20, 30};
// The array name 'numbers' decays to a pointer to numbers[0]
int *ptr = numbers;
printf("First element via array: %d\n", numbers[0]);
printf("First element via pointer: %d\n", *ptr);
return 0;
}
In the example above, ptr = numbers is perfectly valid. The compiler sees numbers and says, "I'll just treat this as the memory address of the very first integer in that block."
When does it NOT decay?
There are only two major exceptions where an array stays an array:
- When used with the
sizeofoperator:sizeof(numbers)returns the size of the entire block, not the size of a pointer. - When using the address-of operator:
&numbersprovides a pointer to the entire array, not just the first element.
Outside of these cases, treat the array name as a shortcut to the first element's address. This is the "magic" that allows C to pass large arrays to functions efficiently; instead of copying the whole building, C just passes the address of the front door.
Key takeaway
Array decay is the automatic conversion of an array's name into a pointer to its first element.