Where is the null character in an empty string with a fixed length?

So, I was curious to read the C code; let's say we have the following code:

char text[10] = "";

Where does the C compiler then put the null character?

I can think of 3 possible cases

  • At the beginning, and then 9 characters of what was previously remembered
  • In the end, so 9 characters of garbage and then trailing '\0'
  • He completely fills it 10 '\0'

The question, depending on any case, is whether to add a final one '\0'at runtime strncpy. If this is case 2 and 3, then this is not necessary, but a good idea; and if this is case 1, then this is absolutely necessary.

What is it?

+4
source share
3 answers

text (.. № 3).

char text[10] = "";

:

char text[10] = { '\0' };

, text , , C11, 6.7.9, 21:

, , , , , , , , .

+5

N1256 ( C99), :

6.7.8

14 , . ( , ) .

"" - , ( ), , , , . , , , :

21 , , , , , , , , .

, , , , .

" " p14:

C, char a[5] = "hello"; , , . : .

+1

"" char[1] C const char [1] ++.

C

chat no_name[] = { '\0' };

++

const chat no_name[] = { '\0' };

, . ,

char text[10] = "";

char text[10] = { '\0' };

, ( , [0]), 0.

C (6.7.9 )

14 UTF-8 , . ( , ) .

21 , , , , , , , ,

, ,

10 , . , , :

- , ;

- , ( ) ;

- , () , ;

- , () , ;

++.

, C , ,

char text[5] = "Hello";
         ^^^

, .:) ,

char text[5] = { 'H', 'e', 'l', 'l', 'o' };
0

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


All Articles