16

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

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

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

4

2 回答 2

31

好吧,您的代码使用结构而不是指向结构的指针。有多种方法可以满足您的需求,包括:

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 问题)。

于 2008-10-11T23:39:15.747 回答
0

这对我有用:


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找到了这些信息

于 2008-10-11T23:45:26.077 回答