0

In C, why we are declaring arrays that has strings using

char* arr[] = {"PYTHON","JAVA","RUBY","C++"};

instead of

char arr[] = {"PYTHON","JAVA","RUBY","C++"};

Why it returns error "excess elements in char array initializer" and what does it means? Also what really happens underneath the first one?

PLSmA1
  • 23
  • 1
  • 4
  • For one, `char arr[] = {"PYTHON","JAVA","RUBY","C++"};` certainly isn't doing what you think it is. If you have a question about a warning or error, *always* post the error verbatim [in your question](https://stackoverflow.com/posts/59057575/edit), and describe what part(s) of it you find confusing. – WhozCraig Nov 26 '19 at 18:50
  • Because strings are actually arrays in C. – ggorlen Nov 26 '19 at 18:50

1 Answers1

1

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' };
Steve Summit
  • 45,437
  • 7
  • 70
  • 103