简体   繁体   English

为什么sizeof无法正常工作?

[英]Why doesn't sizeof work as expected?

#include <stdio.h> 

int main(void) 
{   
    printf("%d", sizeof (getchar()) );
}

What I expect is, 我期望的是
1. Type input. 1.键入输入。
2. Read input and return input value. 2.读取输入并返回输入值。
3. Evaluate sizeof value. 3.评估sizeof值。
4. Print the sizeof value. 4.打印sizeof值。

But the first step never happens. 但是第一步永远不会发生。

Why doesn't the first step happen? 为什么第一步没有发生?

The sizeof operator does not evaluate its operand unless its type is a variable length array type: It looks at the type and returns the size. 除非其类型为可变长度数组类型,否则sizeof运算符不评估其操作数:它查看该类型并返回大小。 This is perfectly safe: 这是绝对安全的:

char *ptr = NULL; // NULL ponter!
printf("%zu", sizeof *ptr);

It will return 1 , since it does not have to evaluate the expression to know the answer. 它将返回1 ,因为它不必评估表达式即可知道答案。

What I expect is, 1. Type input. 我期望的是,1.输入。 2. Read input and return input value. 2.读取输入并返回输入值。 3. Evaluate sizeof value 4. Print the sizeof value. 3.评估sizeof值。4.打印sizeof值。

But the first step never happens. 但是第一步永远不会发生。 Why doesn't the first step happen? 为什么第一步没有发生?

Because, with a very few exceptions, the sizeof operator does not evaluate its operand. 因为除了极少数例外, sizeof运算符不会评估其操作数。 Your usage is not one of the exceptions. 您的用法不是例外之一。 Not evaluating getchar() means getchar() is not called. 不评估getchar()意味着未调用getchar()

In any event, I'm not sure what you expect from your code. 无论如何,我不确定您对代码的期望。 Even if getchar() were called, the result always has the same type ( int ), which does not depend on the input. 即使getchar() 调用时,结果总是相同的类型( int ),它不依赖于输入。

Do also pay attention to @PP's comments. 也要注意@PP的评论。 Your printf() format does not match the type of the data being printed, size_t . 您的printf()格式与要打印的数据类型size_t不匹配。 As he observes, the printf() call has undefined behavior as a result. 正如他所观察到的,结果是printf()调用具有未定义的行为。

Because getchar() return type is an int , not a char . 因为getchar()返回类型是int ,而不是char sizeof(int) is 4 on your platform. 您的平台上的sizeof(int)为4。

Also, you should use %zu to print size_t values. 另外,您应该使用%zu打印size_t值。 Using incorrect format specifier is technically undefined behaviour . 使用不正确的格式说明符在技术上是未定义的行为

In C the sizeof operator is evaluated at run-time only for Variable Size Arrays (VLA). 在C语言中,sizeof运算符仅在运行时针对可变大小数组(VLA)进行评估。 In all other cases the operator does nor evaluate its operand. 在所有其他情况下,运算符都不会评估其操作数。 It deduces the type of the expression and returns the size of object of the deduced type. 它推导表达式的类型,并返回推导类型的对象的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM