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:
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:
printArray
, we can't directly determine the size of myArray
.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:
sizeof
 or &
 (address-of) operators.char
 arrays).Understanding array decay is crucial for working effectively with C-style arrays and functions in C++.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible