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 ints. 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 of myArray.
  • 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

sizeof and C-Style Arrays
Why does sizeof return the total bytes of a C-style array, but return the size of a pointer when the array is passed to a function?
Out of Bounds Access in C-Style Arrays
What happens if I try to access an element outside the bounds of a C-style array?
C-Style Array Initialization
What are the different ways to initialize a C-style array in C++?
Alternatives to C-Style Arrays
What are some alternatives to using C-style arrays in C++?
2D C-Style Arrays
How do I create and work with 2D C-style arrays in C++?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant