C-Style Arrays

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?

Abstract art representing computer programming

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.

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