C++: size of a char array using sizeof

自作多情 提交于 2020-01-03 08:30:09

问题


Look at the following piece of code in C++:

char a1[] = {'a','b','c'};
char a2[] = "abc";
cout << sizeof(a1) << endl << sizeof(a2) << endl;

Though sizeof(char) is 1 byte, why does the output show sizeof(a2) as 4 and not 3 (as in case of a1)?


回答1:


C-strings contain a null terminator, thus adding a character.

Essentially this:

char a2[] = {'a','b','c','\0'};



回答2:


That's because there's an extra null '\0' character added to the end of the C-string, whereas the first variable, a1 is an array of three seperate characters.

sizeof will tell you the byte size of a variable, but prefer strlen if you want the length of a C-string at runtime.




回答3:


For a2, this is a string so it also contains the '\n'

Correction, after Ethan & Adam comment, this is not '\n' of course but null terminator which is '\0'



来源:https://stackoverflow.com/questions/10735990/c-size-of-a-char-array-using-sizeof

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