I am learning C++, and read that when an array is passed into a function it decays into a pointer. I wanted to play around with this and wrote the following function:
void size_print(int a[]){
cout << sizeof(a)/sizeof(a[0]) << endl;
cout << "a ->: " << sizeof(a) << endl;
cout << "a[0] ->" << sizeof(a[0]) << endl;
}
I tried inputting an array with three elements, let's say
int test_array[3] = {1, 2, 3};
With this input, I was expecting this function to print 1, as I thought a
would be an integer pointer (4 bytes) and a[0]
would also be 4 bytes. However, to my surprise the result is 2 and sizeof(a) = 8
.
I cannot figure out why a
takes up 8 bytes, but a[0]
takes up 4. Shouldn't they be the same?