Home > Software design >  Why the size differs? sizeof(a) vs sizeof(&a) of an array?
Why the size differs? sizeof(a) vs sizeof(&a) of an array?

Time:09-09

For the below code.

int a[4];
printf("%d\n",sizeof(a));
printf("%d\n",sizeof(&a));

The output is

16
8

'a' represents the whole array (Also, the address of the first element of the array since it is a 1D array), and sizeof(a) represents the size of the whole array. Hence the size is 16. Understood.

'&a' represents the address of the whole array, and but sizeof(&a) represents what?

I guess its output came as 8 because the value is an address and calculating the size of a pointer which is fixed? Hence 8. Am I right?

But I still didn't get clarity. Can anyone help to give a clear explanation?

CodePudding user response:

Because, they differ in type, and sizeof operator operates on the type.

First, sizeof operator yields a result of type size_t. You should use %zu format specifier to print the result.

That said, in this case, a is the array (and this is one specific use case where array does not "decay"), so, it calculates the size as number of element multiplied by size of each element. In your case, the size of an int is supposed to be 4, so you get 4*4, 16. For understanding, below print statements are similar:

printf("%zu\n",sizeof(a));
printf("%zu\n",sizeof(int[4])); // same as above

On the other hand, &a represents the address of the array, and that address is a pointer, of type int (*)[4]. Again, your system seems to use 8 bytes as pointer size, hence the output. To compare, we can write

printf("%zu\n",sizeof(&a));
printf("%zu\n",sizeof(int(*)[4])); // same as above

CodePudding user response:

The expression &a returns a pointer to a.

A size of  a  the pointer in your system is 8 bytes.

CodePudding user response:

I guess its output came as 8 because the value is an address and calculating the size of a pointer which is fixed? Hence 8. Am I right?

Yes - the expression &a yields a pointer to a, which has type int (*)[4] (pointer to 4-element array of int). On your system, that pointer type is 8 bytes wide.

So,

sizeof a  == sizeof (int [4])    == 16
sizeof &a == sizeof (int (*)[4]) == 8
sizeof *a == sizeof a[0] == sizeof (int) == 4

Different pointer types may have different sizes, but on most desktop and server systems all object pointers will be the same size (either 4 or 8 bytes depending on the architecture).

Side note: sizeof is an operator, not a function - parentheses are only required if the operand is a type name. It doesn't hurt anything to write sizeof (a) instead of sizeof a and I know some people here recommend it, but personally I tend not to.

  • Related