Search code examples
carraysenumsinitializationdesignated-initializer

Initialize array of strings indexed by enumeration in C


I am hoping to make an array of strings based on an enumeration in C programming language. Ideally I would like to declare this as a constant, so I would like to declare it at compile time rather than fill it in during my program execution.

As an example, say I have an enumeration:

enum example
{
 RED=0,
 YELLOW,
 BLUE
};

I would like to initialize an array of strings as such:

array[RED]= "apple";
array[YELLOW] = "school bus";
array[BLUE] = "Ocean";

Is there a way that I can declare this as a constant something along the lines of:

const char array[3][12] = 
{
 array[RED]= "apple", 
 array[YELLOW] = "school bus", 
 array[BLUE] = "Ocean"
}; 

Rather than having to fill in an array of strings as:

const char array[3][12] = {"apple", "school bus", "Ocean"};

Solution

  • You can do it for example the following way

    enum example {  RED = 0,  YELLOW,  BLUE };
    
    const char array[3][12] = 
    {
        [RED] = "apple", 
        [YELLOW] = "school bus", 
        [BLUE] = "Ocean"
    };