如何初始化指向结构的指针数组?

是否可以初始化一个指向结构的指针数组? 就像是:

struct country_t *countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} } 

我想这样做是为了让实体在不连续的内存中,并在连续的内存中指向它们……但我不能使用动态内存,所以我想知道没有它是否可行。

好吧,您的代码使用结构而不是指向结构的指针。 有办法做你想要的,包括:

 static struct country_t us = { "United States of America", "America" }; static struct country_t uk = { "England", "Europe" }; static struct country_t et = { "Ethiopia", "Africa" }; struct country_t *countries[] = { &us, &uk, &et, }; 

在C99中,还有其他方法可以使用指定的初始值设定项和复合文字。 第6.5.2.5节“复合文字”显示方式:

 struct country_t *countries[] = { &(struct country_t) { "United States of America", "America" }, &(struct country_t) { "England", "Europe" }, &(struct country_t) { "Ethiopia", "Africa" }, }; 

该标准说明了具有函数调用的结构的指针。 请注意,并非所有C编译器都接受C99语法,并且这些复合文字在C89(又名C90)中不存在。

编辑:已升级为使用2个字母的ISO 3166国家/地区代码。 还将命名结构变为静态变量 – 这些符号在文件之前不可见(因为它们不存在),现在它们在文件之后也不可见。 我争论是否要制作任何const并且决定不 – 但是当你可以使用const时通常是一个好主意。 此外,在这个例子中,有3个大陆的3个国家。 如果您在一个大洲(标准)中拥有多个国家/地区,您可能希望能够共享大陆字符串。 但是,你是否可以安全地(或根本不能)这样做取决于struct country_t (未给出)的详细信息,以及是否允许程序更新表(返回到const-ness问题) 。

这对我有用:

 struct country_t { char *fullname; char *shortname; }; struct country_t countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} }; int main(int argc, char *argv[]) { return 0; } 

你可以更简洁并使用:

 struct country_t { char *fullname; char *shortname; } countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} }; int main(int argc, char *argv[]) { return 0; } 

编辑:我在The C Book找到了这个信息