开发者

Unexpected results for "sizeof" of strings

Why would sizeof in the following ca开发者_JS百科ses 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?


Strings in C are null terminated.

"ab" in memory looks like 'a' 'b' '\0'

While t is a pointer, so size is 4.


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.


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.


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜