问题
Why would sizeof in the following cases print different values:
printf("%d",sizeof("ab")); //print 3
char* t="ab";
printf("%d",sizeof(t)); //print 4
In the first case I have 2 characters... Shouldn't sizeof
print 2? Because they are 2 bytes?
回答1:
Strings in C are null terminated.
"ab" in memory looks like 'a' 'b' '\0'
While t
is a pointer, so size is 4.
回答2:
t
is a pointer to an array containing "ab"
. Its size is the size of a pointer.
"ab"
is an array containing "ab"
. Its size is the size of that array, which is three characters because you have to account for the null terminator.
Arrays are not pointers.
回答3:
Because in the first case you are asking for the sizeof an array. The second time you are asking for the size of a pointer.
回答4:
A string literal is a char array, not a char *.
char a[] = "ab";
char * t = a;
printf("%d",sizeof(a)); //print 3
printf("%d",sizeof(t)); //print 4
回答5:
The type of the string literal "ab"
is const char(&)[3]
.
So sizeof("ab") = sizeof(const char(&)[3]) = sizeof(char) * 3
which is 3 on your machine.
And in the other case, t
is just a pointer.
So sizeof(t) = sizeof(void*)
which is 4 bytes on your machine.
--
Note:
If you prepend "ab"
with L
, and make it L"ab"
, then,
The type of the string literal L"ab"
is const wchar_t(&)[3]
.
So sizeof(L"ab") = sizeof(const wchar_t(&)[3]) = sizeof(wchar_t) * 3
which is 12 on ideone:
http://ideone.com/IT7aR
So that is because sizeof(wchar_t) = 4
on ideone which is using GCC to compile!
来源:https://stackoverflow.com/questions/5463325/unexpected-results-for-sizeof-of-strings