Home > Net >  How to define a 2D array of strings for different (human) languages in C
How to define a 2D array of strings for different (human) languages in C

Time:08-05

I am attempting to create an array of strings in C to be used in an embedded application that I can easily reference what string and what language that string should be in.

To do this, I am trying to create a constant 2-dimensional array of constant character pointers, and index them with enums as follows:

typedef enum _available_languages_enum_t
{
    ENGLISH = 0,
    FRENCH
} available_languages_enum_t;

typedef enum _strings_lookup_enum_t
{
    STR_HELLO = 0,
    STR_WORLD
} strings_lookup_enum_t;

char const * const strings[][] = {
    {
        "Hello",
        "world"
    },
    {
        "Bonjour",
        "le monde"
    }
};

I then intend to get the string as needed

printf("%s %s\r\n", strings[ENGLISH][STR_HELLO], strings[ENGLISH][STR_WORLD]);
printf("%s %s\r\n", strings[FRENCH][STR_HELLO], strings[FRENCH][STR_WORLD]);

Expected output:

Hello world
Bonjour le monde

My syntax of trying to create the array does not seem to be right, and getting an error an array may not have an element of this type.

Is it possible to create a constant multi-dimensional array like what I am trying to do here? Or am I digging down the wrong path?

CodePudding user response:

You cant declare the array without at least one bound.

typedef enum _available_languages_enum_t
{
    ENGLISH = 0,
    FRENCH
} available_languages_enum_t;

typedef enum _strings_lookup_enum_t
{
    STR_HELLO = 0,
    STR_WORLD,
    STR_LAST_TERMINATING,
} strings_lookup_enum_t;

char const * const strings[][STR_LAST_TERMINATING] = {
    {
        "Hello",
        "world"
    },
    {
        "Bonjour",
        "le monde"
    }
};

CodePudding user response:

'0_____' gave you the solution.

In the long run, when your language collection and word list grows, you'll wish you'd swapped "what goes with what."

I relocated the ENDLIST to the list of language enums:

typedef enum _available_languages_enum_t
{
    ENGLISH = 0,
    FRENCH,
    ENDLIST,
} available_languages_enum_t;

Then:

char const * const strings[][ ENDLIST ] = {
    {
        "Hello",
        "Bonjour",
    },
    {
        "world",
        "le monde",
    },
};

int main( void ) {
    int i = ENGLISH;
    printf("%s %s\n", strings[STR_HELLO][ i ], strings[STR_WORLD][ i ]);
    i = FRENCH;
    printf("%s %s\n", strings[STR_HELLO][ i ], strings[STR_WORLD][ i ]);
    return 0;
}

Is the important thing the 'language', or is it the 'word', with language being set only once?

  • Related