How to find array length in C++? Problem with sizeof and pointers
Hello everyone! I'm a beginner C++ developer and I've encountered a very strange problem. I need to find out how many elements are in an array, but my attempts are failing.
I write like this:
```cpp
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Array length: " << size; // Outputs 5 — correct
```
But when I try to do the same inside a function, passing the array as a parameter, I get nonsense:
```cpp
void printArrayLength(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Array length: " << size; // Outputs 1 or 2, but not 5!
}
int main() {
int myArray[] = {10, 20, 30, 40, 50};
printArrayLength(myArray);
return 0;
}
```
Why does this happen? sizeof(arr) inside the function does not give the size of the entire array, but what
No answers yet.
Log in to leave an answer