C-Style Arrays

C-Style Array to Pointer Decay

What does it mean when a C-style array "decays" to a pointer?

Abstract art representing computer programming

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++.

This Question is from the Lesson:

C-Style Arrays

A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

C-Style Arrays

A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved