Statement char txt[20]="Hello World!\0"
comprises actually two parts, a definition part and an initialization part. char txt[20]
, the definition part, tells the compiler to reserve 20 elements of size of character (in this case 20 bytes), regardless of the content with which you will initialize the array later on. The initialization part ="Hello World!\0"
then "prefills" the reserved memory with the characters of literal Hello World!\0
. Note that it is actually not necessary to write \0
explicitly in the string, since string literals are by itself terminated by the \0
-character. So you should write char txt[20]="Hello World!"
. It is OK if the length of the string literal is smaller than the memory allocated; If the length of the string literal used for initializing exceeds the length of the array, you get at least a compiler warning.
Note, however, that if you write char txt[]="Hello World!"
, the length of the memory reserved will be exactly the length of the initial string literal.
Concerning array initialization, you might confer to cppreference.com. Concerning the discussion on "variable definition" versus "variable declaration", I find this SO answer very helpful.