Operator sizeof() in C

巧了我就是萌 提交于 2019-12-07 06:24:24

问题


Consider the program

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

output from a gcc compiler is:

4 2 4

Why is it so?


回答1:


Assuming you are running on a 32-bit system:

sizeof a character literal '3' is 4 because character literals are ints in C language (but not C++).

sizeof "3" is 2 because it is an array literal with length 2 (numeral 3 plus NULL terminator).

sizeof literal 3 is 4 because it is an int.




回答2:


A few points to keep in mind:

  1. sizeof isn't a function, it's an operator. It returns the size of a type in units of sizeof char. In other words sizeof char is always 1.
  2. '3' is an int
  3. "3" is a char[2], the character 3 then the null terminator.
  4. 3 is an int

With these the differences are easily explained:

  1. an int requires 4 chars of space to hold it
  2. char[2] naturally only requires 2 chars



回答3:


To quote 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.




回答4:


sizeof() Output depends on compiler you are using



来源:https://stackoverflow.com/questions/3334233/operator-sizeof-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!