[Error] too many initializers for char array

Hey seniors,

I am facing a problem of initialization of character array, it gives error of too much initializer.

1
2
3
4
 int n=12;
	char *ptr;
	char array[n]= {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	ptr=array;
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main()
{
   const char * array[12]= {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

   for ( auto a : array ) cout << a << '\n';
}
The important point here is that a char array[] is an array of characters, i.e. a single string. So at line 3, you're trying to initialise a single string as if it were an array of strings.

As lastchance has shown you, if you want an array of strings, you should use a char* array[] instead, and because your strings are string literals, they should actually be const char*.

EDIT: Also, this is a duplicate of http://www.cplusplus.com/forum/beginner/264013/ . Please DON'T waste people's time by posting multiple threads for the same topic.
Last edited on
The right solutions is not to use C code when programming with C++.
Not to use pointer.
Use std Container and tools. And give the variable a better name

1
2
       std::array<std::string_view, 12> months {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
       for(auto a : months) std::cout << a << '\n';
Topic archived. No new replies allowed.