3

我正在寻找 C 中的数据结构,它允许我使用压缩语法(如下所示)声明和初始化数百个字符串,这在 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"
}

编辑:我已经意识到在头文件中我可以公开所有字符串,而无需将它们包装在结构中或将它们外部化,并实现主要意图,每个字符串一行:

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

2 回答 2

6

你所拥有的已经几乎是正确的。但是,您不能像这样交错声明和初始化。这是一个更正的示例:

struct
{
    const char* language_hello[NUM_LANGUAGES];
    const char* language_goodbye[NUM_LANGUAGES]; 
} language_string = {
    {"Hello",     "Hola",     "Bonjour"},
    {"Goodbye",   "Adiós",    "Au revoir"}
};
于 2012-08-22T05:52:05.470 回答
0

为了便于代码维护,我建议使用类似于以下的语法:

#define NUM_LANGUAGES 3

typedef struct
{
    const char* hello[NUM_LANGUAGES];
    const char* goodbye[NUM_LANGUAGES];
} language_t;


const char* STR_HELLO [NUM_LANGUAGES] =
{
  "Hello",
  "Hola",
  "Bonjour"
};

const char* STR_GOODBYE [NUM_LANGUAGES] =
{
  "Goodbye",
  "Adiós",
  "Au revoir"
};


int main()
{
  language_t lang =
  {
    { STR_HELLO[0],   STR_HELLO[1],   STR_HELLO[2]   },
    { STR_GOODBYE[0], STR_GOODBYE[1], STR_GOODBYE[2] }
  };
}
于 2012-08-22T06:47:41.683 回答