c - 地址作为 sizeof() 运算符中的操作数

标签 c sizeof

我只是在尝试一个例子,当一个地址作为参数传递给 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/

相关文章:

c - *((uint32_t *) 从内存空间读取

c - 使用 gcc 4.4.3 的 ubuntu 上的 gdb 问题

c - 是否对存在明确定义的同名类型的变量使用 sizeof?

c - 正确使用 fgets()

c - 作为结构变量传递的整数数组

c - 你可以在 double 中存储多大的数字,在 c 中用 float 存储?

c++ - Sizeof() 的 VBA 等价物?

c - fscanf 段错误读入数组

c - 使用 gcc mingw 嵌入二进制 blob

c - 尝试用信号量编写一个简单的程序