[英]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. 请解释一下。
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
。
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。
sizeof ( 3 )
, it is size of int
which is 4
on your machine. sizeof ( 3 )
,它的大小为int
,在你的机器上为4
。
First off, a couple of notes: 首先,几个笔记:
-Wall
. 在GCC上,你通常会使用-Wall
。 This should give you a warning about your format string. 这应该会给你一个关于你的格式字符串的警告。 %zu
instead of %d
as explained in How to print size_t variable portably? 在C99中,您应该使用%zu
而不是%d
如如何以便携式打印size_t变量中所述? . 。 The C standard says the type of the result of sizeof
is size_t
(§6.5.3.4/5). C标准说sizeof
的结果sizeof
是size_t
(§6.5.3.4/ 5)。 It is undefined behavior if your conversion specifiers don't match your arguments. 如果您的转换说明符与您的参数不匹配,则它是未定义的行为 。 Onto your question. 在你的问题上。
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所解释的那样:
sizeof("f") must return 2, one for the 'f' and one for the terminating '\\0'. sizeof(“f”)必须返回2,一个用于'f',一个用于终止'\\ 0'。
[...] [...]
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 数组没有衰减成指针的异常?
sizeof(3)
is sizeof(int)
. 最后, sizeof(3)
是sizeof(int)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.