gpt4 book ai didi

c - 结构数组的初始化会初始化单个元素的所有成员,为什么?

转载 作者:太空狗 更新时间:2023-10-29 14:51:10 25 4
gpt4 key购买 nike

为什么有人会这样做?更好的是,这究竟是如何工作的?我本以为这会以某种方式创建一个包含三个结构的数组,其中只定义了第一个成员。我意识到一个指针指向数组的第一个元素,我知道它是如何工作的,但它的定义方式让我失望! (海合会 4.8.4)

void do_something(const void *);

typedef struct{

int a;
char b;
int c;

} the_data_t;

int main(int argc, char *argv[])
{
the_data_t my_data[] = {10, 'a', 30};
do_something((const void *)my_data);
}

void do_something(const void *data)
{
printf("data a: %d\ndata b: %c\ndata c: %d\n", ((the_data_t*)data)->a,
((the_data_t*)data)->b, ((the_data_t*)data)->c);
}

输出

data a: 10
data b: a
data c: 30

无论如何,我把它改成了这个..

int main(int argc, char *argv[])
{
the_data_t my_data = {10, 'a', 30};
do_something(&my_data);
}

最佳答案

I would have assumed this would somehow create an array of three structures with only the first member defined

不,不是那样的。基本上,它创建一个包含一个元素的数组,并初始化所有成员。

引用 C11,第 6.7.9 章

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union. [...]

Each designator list begins its description with the current object associated with the closest surrounding brace pair. Each item in the designator list (in order) specifies a particular member of its current object and changes the current object for the next designator (if any) to be that member.150) The current object that results at the end of the designator list is the subobject to be initialized by the following initializer.

[...] If the initializer of a subaggregate or contained union begins with a left brace, the initializers enclosed by that brace and its matching right brace initialize the elements or members of the subaggregate or the contained union. Otherwise, only enough initializers from the list are taken to account for the elements or members of the subaggregate or the first member of the contained union; [...]

基本上,您的代码理想情况下应该看起来像

the_data_t my_data[] = {{10, 'a', 30}}; 

可视化初始化一个元素。

OTOH,你所期望的可以通过

实现
 the_data_t my_data[] = {{10}, {'a'}, {30}};

它创建了一个包含 3 个元素的数组,所有元素都初始化了成员变量 a


也就是说,

 the_data_t my_data[] = {{10, 'a', 30}};

相当于写

 the_data_t my_data = {10, 'a', 30};

除了 my_data 部分将不再是数组(但是一般来说,单元素数组有什么好处?)。

关于c - 结构数组的初始化会初始化单个元素的所有成员,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38900556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com