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