Unexpected results for “sizeof” of strings

半世苍凉 提交于 2019-12-10 18:55:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!