C-Style Array to Pointer Decay
What does it mean when a C-style array "decays" to a pointer?
When we say a C-style array "decays" to a pointer, we're referring to the automatic conversion of an array to a pointer to its first element in certain situations.
This happens when:
- An array is passed to a function.
- An array is used in an expression where a pointer is expected.
Here's an example:
void printArray(int arr[]) {
// Here, arr has decayed to a pointer
// to the first element
}
int main() {
int myArray[3] = {1, 2, 3};
// Array decays to pointer here:
printArray(myArray);
}
In main
, myArray
is an array of 3 int
s. But when it's passed to printArray
, it decays to an int*
pointing to the first element.
This decay has some important implications:
- The size information of the original array is lost. Inside
printArray
, we can't directly determine the size ofmyArray
. - We can modify the original array through the decayed pointer, as it still points to the original array's memory.
The decay is why we often need to pass the size of an array as a separate parameter to functions that work with arrays.
Note that array decay does not happen when:
- The array is the operand of the
sizeof
or&
(address-of) operators. - The array is initialized with a string literal (for
char
arrays).
Understanding array decay is crucial for working effectively with C-style arrays and functions in C++.
C-Style Arrays
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible