问题
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:
sizeof ( '3')
, it is the size of character constant which isint
so you are getting value as4
on your machine.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.sizeof ( 3 )
, it is size ofint
which is4
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 ofsizeof
issize_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
, sosizeof('3')
issizeof(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 wheresizeof(int)
is 4. Sincesizeof(char)
is 1, it will equal the amount of characters in a string literal. As explained by Jonathan Leffler:sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'.
[...]
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)
issizeof(int)
.
来源:https://stackoverflow.com/questions/26416703/please-explain-the-output-of-sizeof