0

Say I have a code:

int a[5];
printf("%d %d %d",sizeof(a));

The output is

20

As a is a constant pointer pointing to the integer a[0], shouldn't the sizeof(a) be 4 bytes, instead why is it 20 bytes?

Arjun Ashok
  • 53
  • 1
  • 8
  • 3
    `As a is a constant pointer pointing to the integer a[0]` It isn't. Its an array. – tkausl Oct 06 '18 at 10:23
  • 1
    An array is decyed to the pointer to its 1st element when being used as argument to a function. `sizeof` is *not* a function. `sizeof` is an operator. So there is *no need* to wrap the variable `a` in parenthesis. `sizeof a` would just do and (in your example) will evaluate to `20`. – alk Oct 06 '18 at 10:28
  • 1
    Do yourself a favor and turn on **all** your compiler warnings, and mind them. – pmg Oct 06 '18 at 10:34

2 Answers2

2

As a is a constant pointer pointing to the integer a[0], shouldn't the sizeof(a) be 4 bytes, instead why is it 20 bytes?

Wording is important. As stated in the comments, a isn't a pointer, its an array.

a gets converted to a pointer to its first element in most cases, but not all. One such exception is when it is the operand of the sizeof operator. So the sizeof will be similar to sizeof(int[5]) (and not sizeof(int*) as you expected) which returns 5 * sizeof(int). The result, as you can see, will most likely be 20 as sizeof(int) is 4 on most systems.


Side note: I assume you meant printf("%d", sizeof(a)); instead of using three format specifiers. And you should be using %zu there as sizeof returns a size_t, not an int.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

It's a array so there are 5 elements as 0,1,2,3,4 so one element is 4 bytes then 5 elements should be 20 bytes. you can get sizeOf as

printf("%d", sizeof(a));

rehan
  • 469
  • 1
  • 7
  • 17