简体   繁体   中英

error: excess elements in char array initializer

I am creating a weather report for college assignment. I working on a function that is suppose to print out the data for all 12 months. I have an array that is 12 in size and holds the name of the 12 months. When I compile the program I keep getting the following error:

assignment3.c:149:5: error: excess elements in char array initializer

Here is the function that has this array:

    void printMonthlyStatistic(int month,const struct MonthlyStatistic* monthly){

    int i;
    char monthNames[12] = {"January", "February", "March", "April", "May", "June", "July", "August",
                           "September", "October", "November", "December"};

    for (i=0;i<12;i++) {

        printf(" %c | %.1f | %.1f | %.1f | %.1f \n",monthNames[i],monthly->maxTemperature,monthly->minTemperature,monthly->averageTemperature,
                                                    monthly->totalPrecipitation);
    }

}

You have defined an array of individual char values and since the elements are string literals and consist of more than one character there are excess elements in your initializer and hence the error message.

Instead you could define an array of char* where each element will point to the start of each string literal in the array.

const char* monthNames[12] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

As these strings will probably end up in the read only data segment of your binary. It wont hurt to declare them const .

In your code

char monthNames[12]

represents an array of char, not a string, but a single character. You must change your array to something like this:

char* montNames[12]

in order to have an array of strings and not a simple character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM