How to compute the size of an array CPP?
C++
// A C++ program to show that it is wrong to // compute size of an array parameter in a function #include <iostream> using namespace std; void findSize( int arr[]) { cout << sizeof (arr) << endl; } int main() { int a[10]; cout << sizeof (a) << " " ; findSize(a); return 0; } |
Output
40 8
Time Complexity: O(1)
Auxiliary Space: O(n) where n is the size of the array.
The above output is for a machine where the size of an integer is 4 bytes and the size of a pointer is 8 bytes.
The cout statement inside main() prints 40, and cout in findSize() prints 8. The reason for different outputs is that the arrays always pass pointers in functions. Therefore, findSize(int arr[]) and findSize(int *arr) mean exact same thing. Therefore the cout statement inside findSize() prints the size of a pointer.
For details, refer to the following articles:
Contact Us