Search code examples
c++initializer-list

C++ "Too many initializers" Error while making an array of chars


I'm new to C++. I know a lot of python but I'm extremely new to C++. I was creating an array of chars but I got this error- "Too many Initializers" in VSCode. Please let me know how to fix it. Here's the code

1 | class Board {
2 |     public:
3 |     char pos_list[9];
4 | 
5 |     void reset_pos() {
6 |        pos_list[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
7 |     };
8 | };

I am getting this error in line 6. Please help me :(


Solution

  • EDIT: My initial answer was not correct, please find the modified correct way to do what you are looking for:

    You will not be able to use {'','',''} in order to assign empty values to all elements in the array in C++, you can only do that while initializing the array when you declare it. Also, it wouldn't be ideal because it would use hardcoding of ' ' across the entire length of the array. The better way to do this is to loop over the array and then set each element to empty like below:

    void reset_pos() {
               int len = sizeof(pos_list)/sizeof(pos_list[0]);
               for(int i=0; i<len; i++){
                   pos_list[i] = ' ';
               }
            };