Reputation: 910
I was just trying an example and i tried to check the output when an address is passed as an argument in the sizeof
operator and i got output of 4. Now my question is when you pass a pointer in sizeof
operator why is it showing 4 bytes of memory when actually there is no pointer variable, it's just only an address?
#include<stdio.h>
int main()
{
int a=1;
int c;
c=sizeof(&a);
printf("%d\n",c);
return 0;
}
Upvotes: 1
Views: 233
Reputation: 882296
It's because sizeof
returns the size of a type, as per C11 6.5.3.4 The sizeof and _Alignof operators /2
(my emphasis):
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.
The type of &a
where a
is an int
is covered by 6.5.3.2 Address and indirection operators /3
in the same standard:
The unary
&
operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type".
In other words, int a; sizeof(&a)
is functionally equivalent to sizeof(int *)
.
Upvotes: 7
Reputation: 134376
sizeof
operator works on the type of the operand.
Quoting C11
, chapter §6.5.3.4 (emphasis mine)
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. [....]
&a
is of type int *
, so your statement is the same as sizeof(int *)
. The result, is the size of a pointer (to integer), in your platform.
That said, sizeof
produces a type of size_t
as result,
size_t
%zu
to print the result.Upvotes: 4