Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: size of a char array using sizeof

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)?

like image 849
Saad Avatar asked May 24 '12 10:05

Saad


2 Answers

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

Essentially this:

char a2[] = {'a','b','c','\0'};
like image 174
Pubby Avatar answered Oct 13 '22 05:10

Pubby


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.

like image 36
Component 10 Avatar answered Oct 13 '22 05:10

Component 10