I have written this simple program
#include <iostream>
using namespace std;
int main (){
int arr [5] = {1,2,3,4,5};
cout<<arr<<endl; //Line 1
cout<<&arr<<endl; //Line 2
cout<<sizeof(arr)<<endl; //Line 3
cout<<sizeof(&arr)<<endl; //Line 4
}
What I expected was:
- Line 1:
arris the name of the array, and it is a pointer to the first elementarr = &arr[0], hence address of&arr[0]will be printed out - Line 2: address of
arr[0]will be printed out,&arr = arr Line 3:
sizeof(arr)is getting thesizof(a pointer)sincearris a pointer, and I should get4 bytesLine 4:
sizeof(&arr)is the same as Line 3, since&arris of type pointer, and I should get4 bytes
But instead in Line3: I get 20 bytes (sizof(int)*number of integers)
How come in Line2: arr acts like a pointer, and in Line3 it acts as an array
I know that an array is not a pointer, but when passed to a function it decays to a pointer, sizeof(..) is an operator, and hence it treats arr as an array, but so is <<, it is an operator not a function
