Home > Back-end >  Why is this pointer 8 bytes?
Why is this pointer 8 bytes?

Time:11-17

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?

CodePudding user response:

Shouldn't they be the same?

No. a is (meant to be) an array (but because it's a function argument, has been decayed 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.

CodePudding user response:

A pointer is just an address of memory where the start of the variable is located. That address is 8 bytes.

a[0] is a variable in the first place of the array. It technically could be anything of whatever size. When you take a pointer to it, the pointer just contains an address of memory (integer) without knowing or caring what this address contains. (This is just to illustrate the concept, in the example in the question, a[] is an integer array but the same logic works with anything).

Note, the size of the pointer is actually different on different architectures. This is where the 32-bit, 64-bit, etc. comes in. It can also depend on the compiler but this is beyond the question.

CodePudding user response:

The size of the pointer depends on the system and implementation. Your uses 64 bits (8 bytes).

a[0] is an integer and the standard only gives an indication of the minimum max value it has to store. It can be anything from 2 bytes up. Most modern implementations use 32 bits (4 bytes) integers.

sizeof(a)/sizeof(a[0]) will not work on the function parameters. Arrays are passed by the reference and this division will only give you information how many times size of the pointer is larger than the size of an integer, but not the size of the object referenced by the pointer.

  • Related