c - sizeof 运算符在以下代码片段中的行为如何?

标签 c sizeof

请解释以下代码段的 OP:

int *a="";
char *b=NULL;
float *c='\0' ; 
printf(" %d",sizeof(a[1])); // prints 4 
printf(" %d",sizeof(b[1])); // prints 1
printf(" %d",sizeof(c[1])); // prints 4

编译器将 a[1] 解释为 *(a+1) ,所以 a 有一些地址,现在它提前 4 个字节,然后它会有一些垃圾值,所以 OP 4 字节如何,即使我这样做a[0] ,它仍然打印 4 ,虽然它是一个空字符串,但为什么它的大小是 4 个字节?

在这里我们找出指针指向的变量的大小,所以如果我说 a[1] 的大小,它意味着 *(a+1) 的大小,现在 a 有一个字符串常量的地址这是一个空字符串,在我对该地址 +1 后它向前移动 4 个字节,现在它在某个新地址,现在我们如何知道这个值的大小,它可以是整数、字符或 float ,什么,那么如何得出结论呢?

最佳答案

除一种情况外,sizeof 运算符不计算其操作数。

来自 C 标准(6.5.3.4 sizeof 和 alignof 运算符)

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. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

在这段代码中

int *a="";
char *b=NULL;
float *c='\0' ; 
printf(" %d",sizeof(a[1])); // prints 4 
printf(" %d",sizeof(b[1])); // prints 1
printf(" %d",sizeof(c[1])); // prints 4

表达式的类型 a[1]int , 表达式的类型 b[1]char和表达式的类型 c[1]float .

所以 printf相应地调用输出 4 , 1 , 4 .

但是调用中的格式说明符指定不正确。而不是 "%d"必须有 "%zu"因为 sizeof 返回值的类型运算符是 size_t .

来自 C 标准的同一部分

5 The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in <stddef.h> (and other headers).

关于c - sizeof 运算符在以下代码片段中的行为如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003590/

相关文章:

c++ - sizeof 类是否保证只包含元素的大小

c++ - 字符串 "sizeof"的意外结果

c - 当两个管道都属于同一进程时,如何冲洗管道以清理 C 中的缓冲区?

通过更改 makefile 结合 FORTRAN 和 C

c - 宏重新定义逻辑运算符

c - 在 C 中,为什么 sizeof(char) 为 1,而 'a' 是一个 int?

java - 为什么 C 和 Java 的表达式 m++ + (++m) 的输出不同

c - 结构对齐安全使用

c++ - sizeof() 运算符的行为

c++ - 字符串数组上的 Sizeof 运算符在 C++ 中给出不同的输出