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.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to working with classic C-style arrays within C++, and why we should avoid them where possible