[英]Address as a operand in sizeof() operator
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? 我只是在尝试一个示例,当在sizeof
运算符中将地址作为参数传递时,我试图检查输出,并且得到4的输出。现在我的问题是,当在sizeof
运算符中传递指针时,为什么显示4个字节当实际上没有指针变量时,它只是一个地址?
#include<stdio.h>
int main()
{
int a=1;
int c;
c=sizeof(&a);
printf("%d\n",c);
return 0;
}
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): 这是因为sizeof
根据C11 6.5.3.4 The sizeof and _Alignof operators /2
返回类型的大小, C11 6.5.3.4 The sizeof and _Alignof operators /2
(我强调):
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. sizeof运算符产生其操作数的大小(以字节为单位),该操作数可以是表达式或类型的括号名称。 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: 6.5.3.2 Address and indirection operators /3
在同一标准中, 6.5.3.2 Address and indirection operators /3
涵盖了a
是int
的&a
类型:
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)
换句话说, int a; sizeof(&a)
int a; sizeof(&a)
is functionally equivalent to sizeof(int *)
. int a; sizeof(&a)
在功能上等效于sizeof(int *)
。
sizeof
operator works on the type of the operand. sizeof
运算符适用于操作数的类型 。
Quoting C11
, chapter §6.5.3.4 ( emphasis mine ) 引用C11
,第6.5.3.4章( 重点是我的 )
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. sizeof运算符产生其操作数的大小(以字节为单位),该操作数可以是表达式或类型的括号名称。 The size is determined from the type of the operand. 大小由操作数的类型确定。 [....] [....]
&a
is of type int *
, so your statement is the same as sizeof(int *)
. &a
的类型为int *
,因此您的声明与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, 也就是说, sizeof
会产生一种size_t
类型的结果,
size_t
使用类型为size_t
的变量 %zu
to print the result. 使用%zu
打印结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.