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?

When you use sizeof on a C-style array directly, like this:

int myArray[5];
std::cout << sizeof(myArray);

It returns the total bytes used by the array, which is the number of elements multiplied by the size of each element.

However, when you pass an array to a function, it decays to a pointer to the first element. So inside the function, sizeof is actually being applied to a pointer, not the original array:

void myFunction(int arr[]) {
  std::cout << sizeof(arr);
}

int main() {
  int myArray[5];
  myFunction(myArray);
}

In this case, sizeof(arr) inside myFunction will return the size of an int* pointer, not the size of the original myArray.

To avoid this issue, you can pass the size of the array as a separate parameter to the function, or use templates to deduce the array size at compile time.

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.

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++?
C-Style Array to Pointer Decay
What does it mean when a C-style array "decays" to a pointer?
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