C ++: char array size using sizeof

Take a look at the following C ++ code snippet:

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

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

+6
source share
3 answers

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

Essentially this:

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

This is because an extra character '\0' added to the end of line C, while the first variable a1 is an array of three separate characters.

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

+1
source

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

Bugfix, following Ethan and Adam's comment, this is not "\ n", but a null terminator that is "\ 0"

0
source

Source: https://habr.com/ru/post/916549/


All Articles