我只是在尝试一个例子,当一个地址作为参数传递给 sizeof
时,我试图检查输出
运算符,我得到 4 的输出。现在我的问题是,当你在 sizeof
运算符中传递一个指针时,为什么它显示 4 个字节的内存,而实际上没有指针变量,它只是一个地址?
#include<stdio.h>
int main()
{
int a=1;
int c;
c=sizeof(&a);
printf("%d\n",c);
return 0;
}
最佳答案
这是因为 sizeof
根据 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 地址和间接运算符/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 *)
。
关于c - 地址作为 sizeof() 运算符中的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51147839/