简体   繁体   English

请解释sizeof()的输出

[英]Please explain the output of sizeof()

I am new in c programming, and I am trying to understand the sizeof function. 我是c编程的新手,我正在尝试理解sizeof函数。

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 . 我输出为4 2 4

However, I am not able to understand the reason I get this output. 但是,我无法理解我得到此输出的原因。 Kindly explain it. 请解释一下。

  1. sizeof ( '3') , it is the size of character constant which is int so you are getting value as 4 on your machine. sizeof ( '3') ,它是字符常量的大小,它是int因此您在机器上获得的值为4

  2. sizeof ( "3" ) , it is size of string ie 2 . sizeof ( "3" ) ,它是字符串的大小,即2
    String "3" is made of 2 character ('3'+'\\0') = "3" . 字符串"3"由2个字符组成('3'+'\\0') = "3" And we know sizeof(char) is 1. 我们知道sizeof(char)是1。

  3. sizeof ( 3 ) , it is size of int which is 4 on your machine. sizeof ( 3 ) ,它的大小为int ,在你的机器上为4

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.) comp.lang.c FAQ中问题8.9解释了C中的字符常量是int类型,因此sizeof('3')sizeof(int) (在您的机器上看起来是4)。
  • When applied to arrays, sizeof returns the size of the array in bytes. 应用于数组时, sizeof以字节为单位返回数组的大小。 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. 例如, sizeof(int[10])sizeof(int)为4的机器上返回40.因为sizeof(char)是1,它将等于字符串文字中的字符数。 As explained by Jonathan Leffler : 正如Jonathan Leffler所解释的那样:

    1. sizeof("f") must return 2, one for the 'f' and one for the terminating '\\0'. sizeof(“f”)必须返回2,一个用于'f',一个用于终止'\\ 0'。

    2. [...] [...]

    The string literal has the type 'array of size N of char' where N includes the terminal null. 字符串文字的类型为'char的大小为N的数组',其中N包含终止null。

    Remember, arrays do not decay 1 to pointers when passed to sizeof. 请记住, 阵列不衰减通过为sizeof 1时的指针。

    1 Exception to array not decaying into a pointer? 1 数组没有衰减成指针的异常?

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

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

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