In the following code, when I print sizeof(arr)
in main()
, I get output 32. However when I send the same array to a function print()
and print out sizeof(arr)
, I get 8.
My question is, shouldn't they both be 8, because arr
is a pointer to the first element in both cases?
Code:
#include <iostream>
using namespace std;
void print(int arr[])
{
cout << "from function print(): " << sizeof(arr);
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
cout << "from main: " << sizeof(arr) << endl;
print(arr);
return 0;
}
Output:
main.cpp:8:46: warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument]
main.cpp:5:20: note: declared here
from main: 32
from function print(): 8
...Program finished with exit code 0
Press ENTER to exit console.