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?
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?
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
.
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));