I've been trying to find length of an array in C++ and wanted to make it as a function, but even if arrays are reference type sizeof
function does not return same result as ran in
main.
The code below returns the correct result which I need.
int main(){
int arr[] = {3, 71, 223, 696, 21, 453, 231, 422, 22, 32};
int max = arr[0];
uint length = sizeof(arr) / sizeof(*arr);
std::cout << "Length: " << length << std::endl;
return 0;
}
The output is Length: 10
, it's OK.
But if I try to make it a function, here's the example
uint getLength(int *arr){
return sizeof(arr) / sizeof(*arr);
}
int main(){
int arr[] = {3, 71, 223, 696, 21, 453, 231, 422, 22, 32};
std::cout << "Length: " << getLength(arr) << std::endl;
return 0;
}
It returns 2
, therefore the unexpected output is Length: 2
What's causing this situation?
I found the reasonable explanation.
Firstly, I didn't know that C++ does not allow passing arrays completely.
Related to, if parameter is given as integer pointer, sizeof(arr)
is constantly having value as 8
(remember integer pointer size) and sizeof(*arr)
is 4
(remember integer size), because it points to first element of array.