地址作为 sizeof() 运算符中的操作数
Address as a operand in sizeof() operator
我只是在尝试一个例子,当地址作为参数在 sizeof
中传递时,我试图检查输出
运算符,我得到 4 的输出。现在我的问题是,当你在 sizeof
运算符中传递一个指针时,为什么它显示 4 个字节的内存,而实际上没有指针变量,它只是一个地址?
#include<stdio.h>
int main()
{
int a=1;
int c;
c=sizeof(&a);
printf("%d\n",c);
return 0;
}
sizeof
运算符作用于操作数的 type。
引用 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. The size is determined from the type of
the operand. [....]
&a
的类型是int *
,所以你的语句和sizeof(int *)
是一样的。结果是您平台中指针(指向整数)的大小。
也就是说,sizeof
会产生一种类型 size_t
作为结果,
- 使用
size_t
类型的变量
- 使用
%zu
打印结果。
因为 sizeof
returns 类型的大小, 根据 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. The size is determined from the type of the operand.
&a
的类型 a
是一个 int
,在同一标准中被 6.5.3.2 Address and indirection operators /3
覆盖:
The unary &
operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type".
换句话说,int a; sizeof(&a)
在功能上等同于 sizeof(int *)
。
我只是在尝试一个例子,当地址作为参数在 sizeof
中传递时,我试图检查输出
运算符,我得到 4 的输出。现在我的问题是,当你在 sizeof
运算符中传递一个指针时,为什么它显示 4 个字节的内存,而实际上没有指针变量,它只是一个地址?
#include<stdio.h>
int main()
{
int a=1;
int c;
c=sizeof(&a);
printf("%d\n",c);
return 0;
}
sizeof
运算符作用于操作数的 type。
引用 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. The size is determined from the type of the operand. [....]
&a
的类型是int *
,所以你的语句和sizeof(int *)
是一样的。结果是您平台中指针(指向整数)的大小。
也就是说,sizeof
会产生一种类型 size_t
作为结果,
- 使用
size_t
类型的变量
- 使用
%zu
打印结果。
因为 sizeof
returns 类型的大小, 根据 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. The size is determined from the type of the operand.
&a
的类型 a
是一个 int
,在同一标准中被 6.5.3.2 Address and indirection operators /3
覆盖:
The unary
&
operator yields the address of its operand. If the operand has type "type", the result has type "pointer to type".
换句话说,int a; sizeof(&a)
在功能上等同于 sizeof(int *)
。