我怎么能初始化指针数组结构? [英] How can I initialize an array of pointers to structs?

查看:165
本文介绍了我怎么能初始化指针数组结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能初始化数组的指针,以结构?
是这样的:

Is it possible to initialize an array of pointers to structs? Something like:

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

我想要做的是,为了获得不连续的内存实体,以及指向他们连续的内存...但是我不能使用动态内存,所以我不知道是否有可能离不开它。

I want to do that in order to get the entities in not-contiguous memory, and the pointers to them in contiguous memory... But I can't use dynamic memory, so I wonder if it is possible without it.

推荐答案

那么,你的code使用结构,而不是指向结构的指针。有办法做你所追求的,其中包括:

Well, your code uses structures rather than pointers to structures. There are ways to do what you seek, including:

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节复合文字显示方式:

There are other ways to do it with designated initializers and compound literals in C99. Section 6.5.2.5 'Compound Literals' shows the way:

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

The standard illustrates pointers to structures with a function call. Be aware that not all C compilers accept C99 syntax, and these compound literals were not present in C89 (aka C90).

编辑:的升级为使用2个字母的ISO 3166国家codeS。还提出了一个名为结构为静态变量 - 这些符号是不是之前的文件之外可见的(因为它们不存在),而现在他们都没有经过文件之外可见,无论是。我讨论是否做什么const和决定不 - 但是使用常量时,您通常可以是一个好主意。另外,在本例中,有3个国家中3大洲。假如你有一个大陆(规范)多国,您可能希望能够分享大陆的字符串。然而,无论你能做到这一点安全(或全部),取决于对结构country_t (其中未给出),以及程序是否被允许更新细节表(这回来到常量性问题)。

Upgraded to use 2-letter ISO 3166 country codes. Also made the named structures into static variables - those symbols were not visible outside the file before (because they did not exist), and now they aren't visible outside the file after, either. I debated whether to make anything const and decided not to - but using const when you can is generally a good idea. Also, in the example, there are 3 countries in 3 continents. Were you to have multiple countries in a single continent (the norm), you might want to be able to share the continent strings. However, whether you can do that safely (or at all) depends on the details of the struct country_t (which were not given), and on whether the program is allowed to update the table (which comes back to the const-ness question).

这篇关于我怎么能初始化指针数组结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆