gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:08:28 25 4
gpt4 key购买 nike

请解释以下代码段的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com