Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise a structure of arrays of pointers to const strings

Tags:

c

gcc

I am looking for a data structure in C that allows me to declare and initialise hundreds of strings with a compressed syntax, such as that below, is this possible in C11?

#include <stdio.h>

enum {ENGLISH, SPANISH, FRENCH, NUM_LANGUAGES};

struct language_string =
{
    const char* language_hello[NUM_LANGUAGES]   = {"Hello",     "Hola",     "Bonjour"};
    const char* language_goodbye[NUM_LANGUAGES] = {"Goodbye",   "Adiós",    "Au revoir"};
};

void foo(void)
{
    printf(language_string.language_hello[ENGLISH]);        // print "Hello"
}

EDIT: I have come to realise that in a header file I can expose all the strings without wrapping them in a structure or externing them, and achieve the main intent, a single line per string:

const char*  language_hello[NUM_LANGUAGES]   = {"Hello",   "Hola",  "Bonjour"};
const char*  language_goodbye[NUM_LANGUAGES] = {"Goodbye", "Adiós", "Au revoir"};
like image 726
Martin Nichols Avatar asked Dec 01 '25 09:12

Martin Nichols


1 Answers

What you have is already almost right. You can't interleave the declaration and initialization like that, though. Here's a corrected example:

struct
{
    const char* language_hello[NUM_LANGUAGES];
    const char* language_goodbye[NUM_LANGUAGES]; 
} language_string = {
    {"Hello",     "Hola",     "Bonjour"},
    {"Goodbye",   "Adiós",    "Au revoir"}
};
like image 108
Carl Norum Avatar answered Dec 04 '25 01:12

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!