Please explain the output of sizeof()

孤街醉人 提交于 2019-12-01 06:40:40

问题


I am new in c programming, and I am trying to understand the sizeof function.

Please help me understand how this program works:

#include<stdio.h>
main( )
{
    printf ( "\n%d %d %d", sizeof ( '3'), sizeof ( "3" ), sizeof ( 3 ) ) ;
}

I am getting output as 4 2 4.

However, I am not able to understand the reason I get this output. Kindly explain it.


回答1:


  1. sizeof ( '3'), it is the size of character constant which is int so you are getting value as 4 on your machine.

  2. sizeof ( "3" ), it is size of string i.e. 2.
    String "3" is made of 2 character ('3'+'\0') = "3". And we knowsizeof(char) is 1.

  3. sizeof ( 3 ), it is size of int which is 4 on your machine.




回答2:


First off, a couple of notes:

  • You should not omit the return type of main. See What should main() return in C and C++?
  • Enable warnings. On GCC, you would generally use -Wall. This should give you a warning about your format string.
  • In C99, you should use %zu instead of %d as explained in How to print size_t variable portably?. The C standard says the type of the result of sizeof is size_t (§6.5.3.4/5). It is undefined behavior if your conversion specifiers don't match your arguments.

Onto your question.

  • In the comp.lang.c FAQ, question 8.9 explains that character constants in C are of type int, so sizeof('3') is sizeof(int) (which appears to be 4 on your machine.)
  • When applied to arrays, sizeof returns the size of the array in bytes. For example, sizeof(int[10]) returns 40 on a machine where sizeof(int) is 4. Since sizeof(char) is 1, it will equal the amount of characters in a string literal. As explained by Jonathan Leffler:

    1. sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'.

    2. [...]

    The string literal has the type 'array of size N of char' where N includes the terminal null.

    Remember, arrays do not decay1 to pointers when passed to sizeof.

    1 Exception to array not decaying into a pointer?

  • And lastly, sizeof(3) is sizeof(int).


来源:https://stackoverflow.com/questions/26416703/please-explain-the-output-of-sizeof

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