问题描述
这是我刚刚在别人的问题中找到的初始化.
Here's initialization I just found in somebody else's question.
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
我以前从未见过这样的东西,也找不到解释 .name 怎么可能是正确的.
我正在寻找的是这个过程是如何一步一步进行的.
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";
还是我完全错了?
推荐答案
这里没有一步一步".当使用常量表达式执行初始化时,该过程本质上是在编译时执行的.当然,如果数组被声明为本地对象,它会在本地分配并在运行时初始化,但这仍然可以认为是一个无法进行有意义细分的单步过程.
There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.
指定初始值设定项允许您为结构对象的特定成员(或数组的特定元素)提供初始值设定项.所有其他成员都被初始化为零.所以,如果 my_data
被声明为
Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data
is declared as
typedef struct my_data {
int a;
const char *name;
double x;
} my_data;
然后你的
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
只是一种更紧凑的
my_data data[4]={
{ 0, "Peter", 0 },
{ 0, "James", 0 },
{ 0, "John", 0 },
{ 0, "Mike", 0 }
};
我希望你知道后者是做什么的.
I hope you know what the latter does.
这篇关于初始化结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!