Does C string initializer not include terminator?

I am a little confused by the following snippets of C code:

printf("Peter string is %d bytes\n", sizeof("Peter")); // Peter string is 6 bytes

This tells me that when C compiles the string in double quotes, it will automatically add an extra byte for the null terminator.

printf("Hello '%s'\n", "Peter");

The function printfknows when to stop reading the string "Peter" because it reaches the terminator zero, so ...

char myString[2][9] = {"123456789", "123456789" };
printf("myString: %s\n", myString[0]);

It printfdisplays all 18 characters, because there are no null terminators (and they would not fit without removing the 9s). Does C add a null terminator in the variable definition?

+5
source share
7 answers

[2] [9]. [9] - ['1', '2' .. '8', '9']. 9 , 9, '\ 0'. char:

char string[2][10] = {"123456789", "123456789"};

.

+24

, '\ 0'. :

char string[2][10] = { "123456789", "123456789" };

, ( 9 ).

+5

C, , C . , ! , char . ( , ) () char. , , .

C , , . , .

, , , , ( ). GCC, , , .

+3

:

char* myString[2] = {"123456789", "123456789" };

.

+2

C , ++ - .

C . , , . :

char  name1[] =  "Harry";   // Array of 6 char

char  name2[6] = "Harry";   // Array of 6 char

char  name3[] =  { 'H', 'a', 'r', 'r', 'y', '\0' };
                            // Same as 'name1' initialization

char  name4[5] = "Harry";   // Array of 5 char, no null char 

++ , . (name4) ++.

+2

, , 0 ? , "9", , , , , 0 ?

0
source

Byte '\ 0' is not a problem. In most cases, if you have this:

char code[9] = "123456789";

The next byte will be outside the edge of the variable, but it will be unused memory and, most likely, will be 0 (if you do not malloc()and do not set values ​​before using them). Therefore, most of the time it works, even if it is bad for you.

If you use gcc, you can also use the -Wall flag or one of the other (millions) warning flags. This may help (not sure).

0
source

All Articles