问题
Possible Duplicate:
Sizeof doesn't return the true size of variable in C
C -> sizeof string is always 8
Sizeof prints out 6 for:
printf("%d\n", sizeof("abcde"));
But it prints out 4 for:
char* str = "abcde";
printf("%d\n", sizeof(str));
Can someone explain why?
回答1:
The string literal "abcde"
is a character array. It is 6 bytes long, including the null terminator.
A variable of type char*
is a pointer to a character. Its size is the size of a pointer, which on 32-bit systems is 4 bytes. sizeof
is a compile time operation†, so it only looks at the variable's static type, which in this case is char*
. It has no idea what's being pointed to.
† Except in the case of variable-length arrays, a feature introduced in the C99 language standard
回答2:
First example, sizeof()
return the length of the plain string.
Second example, sizeof()
return the size of the pointer -> 32bits so 4 bytes.
回答3:
Because here
printf("%d\n", sizeof("abcde"));
is a string, with considering NULL its 6 byte long.
and
char* str = "abcde";
printf("%d\n", sizeof(str));
is a pointer that requires 32bits hence 4 bytes :-)
来源:https://stackoverflow.com/questions/9644267/why-does-sizeof-return-different-values-for-same-string-in-c