By initializing a C char array using curly braces, is it possible to omit the null byte of '\ 0'?

So, I read that:

char pattern[] = "ould";

is basically a simpler way to write:

char pattern[] = { 'o', 'u', 'l', 'd', '\0' };

I understand that a null character \0marks the end of a line, but what if I write it like this:

char pattern[] = { 'o', 'u', 'l', 'd'}; (without \ 0)

It is still compiling.

Where patternwithout \0causes problems because it seems to compile without warnings ( -Wall)

+3
source share
8 answers

, , char, , , . . strlen, strcpy, ... printf %s ..

+10

? char '\ 0' . . , '\ 0', - . , , !

Char . , "\ 0", .

+3

, . strcpy \0, .

+2

, , , , . printf , - % s, "\ 0" .

, , , , .

+2

, - . , strcmp, strcpy, printf. , .

, - .

char c = pattern[2];
+1

Of course, it compiles - this is a valid C program. Problems would arise if you tried to pass a function to your character array that expects a string with zero completion (an array of characters ending in "\ 0").

+1
source

For example, getting the length of a string will produce unpredictable results.
strlen(pattern)

+1
source
char string[] = "abcd"; /*is valid at the end is the \0, 5 chars were allocated*/

char str[3] = {'\0'}; /* all are \0 */

strncpy(str, string, 2); /*strcpy doesn't add \0*/

str[3] = '\0'; /* now is everything fine! */
+1
source

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


All Articles