gpt4 book ai didi

c - 初始化指向 const 字符串的指针数组结构

转载 作者:太空狗 更新时间:2023-10-29 16:08:34 26 4
gpt4 key购买 nike

我正在寻找 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"};

最佳答案

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

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

关于c - 初始化指向 const 字符串的指针数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12066850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com