C String Null Zero?

I have a basic C programming question, here is what it is. If I create an array of characters, and if I wanted to treat this array as a string using the% s conversion code, I must include zero zero. Example:

char name[6] = {'a','b','c','d','e','f'};
printf("%s",name);

Console output for this:

abcdef

Note that there is no zero zero in the last element of the array, but I still print it as a string.

I am new to programming ... Therefore, I am reading a C beginner book, which says that since I do not use zero zero in the last element, I cannot consider it as a string.

This is the same result as above, although I include zero zero.

char name[7] = {'a','b','c','d','e','f','\0'};
printf("%s",name);
+3
source share
5 answers

printf , . , , . , name ( ). , () .

+3

; , , , printf . , " ", - , , .

: NUL, undefined, , - ; , , - , , , .

TL; DR: . , , .

+5

.

- . :

char name[6] = {'a','b','c','d','e','f'};
printf("%s",name);
printf("%d",name[6]);

, , . .

+2

, , 0 + 6. , .

0

. . .

NUL .

char name[7] = "abcdef";
printf("%s",name);

, 1 , NUL.

.

char name[] = "abcdef";
printf("%s",name);

Another method is to point it to a pointer to char.

char *name = "abcdef";
printf("%s",name);
0
source

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


All Articles