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?
>Solution :
Shouldn’t they be the same?
No. a
is (meant to be) an array (but because it’s a function argument, has been adjusted to a pointer to the 1st element), and as such, has the size of a pointer. Your machine seems to have 64 bit addresses, and thus, each address (and hence, each pointer) is 64 bits (8 bytes) long.
a[0]
, on the other hand, is of the type that an element of that array has (an int
), and that type has 32 bits (4 bytes) on your machine.