简体   繁体   English

运算符sizeof()在C中

[英]Operator sizeof() in C

Consider the program 考虑一下该计划

main()  
{  
 printf("%d %d %d",sizeof('3'),sizeof("3"),sizeof(3));  
}

output from a gcc compiler is: gcc编译器的输出是:

4 2 4

Why is it so? 为什么会这样?

Assuming you are running on a 32-bit system: 假设您在32位系统上运行:

sizeof a character literal '3' is 4 because character literals are ints in C language (but not C++). sizeof一个字符文字'3'是4,因为字符文字是C语言中的整数(但不是C ++)。

sizeof "3" is 2 because it is an array literal with length 2 (numeral 3 plus NULL terminator). sizeof“3”是2,因为它是一个长度为2的数组文字(数字3加上NULL终结符)。

sizeof literal 3 is 4 because it is an int. sizeof literal 3是4,因为它是一个int。

A few points to keep in mind: 要记住以下几点:

  1. sizeof isn't a function, it's an operator. sizeof不是函数,它是一个运算符。 It returns the size of a type in units of sizeof char . 它以sizeof char为单位返回类型的sizeof char In other words sizeof char is always 1. 换句话说, sizeof char总是1。
  2. '3' is an int '3'是一个int
  3. "3" is a char[2] , the character 3 then the null terminator. “3”是char[2] ,字符3是null终止符。
  4. 3 is an int 3是int

With these the differences are easily explained: 有了这些差异很容易解释:

  1. an int requires 4 char s of space to hold it 一个int需要4个char的空间S来保存它
  2. char[2] naturally only requires 2 char s char[2]自然只需要2个char

To quote K & R, 引用K&R,

Each compiler is free to choose appropriate sizes for its own hardware, subject only to the the restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer than int, which is no longer than long. 每个编译器都可以自由选择适合自己硬件的大小,只受限于short和int至少为16位,long为至少32位,short不长于int,不超过long 。

sizeof()输出取决于您使用的编译器

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

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