初始化结构数组 [英] Initializing array of structures
问题描述
下面的初始化我只是在别人的问题找到。结果
Here's initialization I just found in somebody else's question.
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
我从来没有见过这样的事情之前,无法找到解释如何。名称可能是正确的。结果
我正在寻找的是如何一步一步这一过程中去。
I never saw something like this before and can't find explanation how is .name possible to be correct.
What I'm looking for is how step by step this process goes.
它看起来像它会:
1) data;
2) *data;
3) (*data).name;
4) (*data).name="Peter";
还是我完全错了?
Or am I totally wrong?
推荐答案
有只有两个在这里打球的语法。
There are only two syntaxes at play here.
-
普通旧数组初始化:
Plain old array initialisation:
int x[] = {0, 0}; // x[0] = 0, x[1] = 0
A 指定初始化器即可。请参阅接受这个问题的答案:如何初始化ANSI C的结构体
A designated initialiser. See the accepted answer to this question: How to initialize a struct in ANSI C
的语法为pretty不言自明,但。您可以初始化是这样的:
The syntax is pretty self-explanatory though. You can initialise like this:
struct X {
int a;
int b;
}
struct X foo = { 0, 1 }; // a = 0, b = 1
或使用任何排序,
or to use any ordering,
struct X foo = { .b = 0, .a = 1 }; // a = 1, b = 0
这篇关于初始化结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!