我在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"};
答案 0 :(得分:6)
你所拥有的几乎已经是正确的。但是,您不能像这样交错声明和初始化。这是一个更正的例子:
struct
{
const char* language_hello[NUM_LANGUAGES];
const char* language_goodbye[NUM_LANGUAGES];
} language_string = {
{"Hello", "Hola", "Bonjour"},
{"Goodbye", "Adiós", "Au revoir"}
};
答案 1 :(得分: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] }
};
}