Please explain the output of sizeof()

最后都变了- 提交于 2019-12-01 08:01:49
  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.

First off, a couple of notes:

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