Fundamentally, a string in C is an array of char
.
Because of the correspondence between arrays and pointers in C, it is very common and very convenient to refer to an array using a pointer to its first element.
So although strings are fundamentally arrays of char
, it is very common to refer to them using pointers to char
.
So char *arr[]
(which has type "array of pointer to char
") is a good way to implement an array of strings.
You can't write
char arr[] = {"PYTHON", "JAVA", "RUBY", "C++"};
because it's a type mismatch (and correspondingly meaningless). If you declare an array of char
, the initializer for it must be characters. So you could do
char arr[] = { 'P', 'Y', 'T', 'H', 'O', 'N' };
Or, as a special shortcut, you could do
char arr[] = "PYTHON";
where the initializer is a single string literal. This string literal is an array of char
, so it's a fine initializer for arr
which is an array of char
. But there's no direct way to pack multiple strings (as in your original question) into a single array of char
.
Of course, there's one more issue, and that's null termination. More precisely, a string in C is a null terminated array of char
. So the "special shortcut"
char arr[] = "PYTHON";
is actually equivalent to
char arr[] = { 'P', 'Y', 'T', 'H', 'O', 'N', '\0' };