Reputation: 483
we know that c inserts the NULL(\0) automatically at the end of an character array.But why it does not insert the NULL character at the end of an Array of pointers to strings.
For Eample: If i write
char name[]={40,20,30,20,22,22,'c','a','b'}
The NULL character will be automatically added. But if i create an array of pointer whose type is Char will not add a null character at the end of array For Example
char *names[]={"aaa","bbb","cccc"}
Upvotes: 1
Views: 189
Reputation: 881113
C does not do that for character arrays (or any other arrays for that matter), it does it for string literals such as "xyzzy"
. The relevant bit of the ISO C standard, C11 6.4.5 String literals /7
:
In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence.
For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence.
The reason it does this is because it knows you want strings to be null terminated, otherwise they're not actually C strings at all.
If you do happen to find a terminator at the end of your non-string-literal character array name
, it's pure coincidence and relying on it is well into undefined behaviour territory.
Upvotes: 2
Reputation: 206567
Your understanding is not correct. You said,
For Eample: If i write
char name[]={40,20,30,20,22,22,'c','a','b'}
The NULL character will be automatically added.
That is not true.
If you use:
char name[] = "abc";
a terminating null character is added but not in the form you are using.
Upvotes: 3