Reputation:
char *a = "string one";
char b[] = "string two";
char c[] = {'s','t','3'};
Are any of the above string examples null
terminated with \0
automatically?
I'm sure the last example isn't.
Upvotes: 0
Views: 411
Reputation: 310930
String literals are character arrays containing sequences of characters ended with the terminating zero character '\0'
. For example this string literal "string one"
has the type char[11]
and can be imagined like
char string_literal[] = { 's', 't', 'r', 'i', 'n', 'g', ' ', 'o', 'n', 'e', '\0' };
In this declaration
char *a = "string one";
the pointer a
is initialized by the address of the first character of the string literal "string one"
.
In this declaration the array b
is initialized by the elements of the string literal "string two"
including its terminating zero character and has the type char[11]
.
char b[] = "string two";
This declaration is equivalent to
char b[] = { 's', 't', 'r', 'i', 'n', 'g', ' ', 't', 'w', 'o', '\0' };
In this declaration
char c[] = {'s','t','3'};
that is equivalent to
char c[3] = "st3"; // non valid in C++ but valid in C
the array c
having the type char[3]
does not contain a string because neither its element is the terminating zero character.
Upvotes: 2