gpt4 book ai didi

c - 初始化指向结构的指针数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:57 25 4
gpt4 key购买 nike

如何在不创建指向这些结构的指针列表的中间数组的情况下初始化结构数组?考虑以下示例代码:

snippets $ cat a2p.c 
struct shape {
int angles;
char shape_name[16];
};
typedef struct shape shape_t;
struct container {
char name[32];
shape_t **elements;
int num_elts;
};
typedef struct container container_t;

shape_t triangle = {
.angles = 3,
.shape_name = {"Triangle"}
};
shape_t rectangle = {
.angles = 4,
.shape_name = {"Rectangle"}
};

container_t c = {
.name = {"Case"},
.elements = {
&triangle,
&rectangle
},
.num_elts =2
};


int main(void) {

return 0;

}

我需要 .elements 成员指向指向 shape_t 结构的指针数组,但这段代码无法编译:

 snippets $ gcc -c a2p.c
a2p.c:24:2: warning: braces around scalar initializer
.elements = {
^
a2p.c:24:2: note: (near initialization for ‘c.elements’)
a2p.c:25:3: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
&triangle,
^
a2p.c:25:3: note: (near initialization for ‘c.elements’)
a2p.c:26:3: warning: excess elements in scalar initializer
&rectangle
^
a2p.c:26:3: note: (near initialization for ‘c.elements’)
snippets $

但是,如果我添加一个中间数组,如下所示:

shape_t *shapes[] = {
&triangle,
&rectangle
};
container_t c = {
.name = {"Case"},
.elements = shapes,
.num_elts =2
};

代码编译正常。我是否可以避免将创建 shapes[] 数组作为中间步骤并直接使用第一个代码片段中的所有数据初始化 container_t?那么正确的初始化语法是什么?

最佳答案

你快到了;你只需要确保 elements 初始化器是一个合适的指针,就像这样:

struct shape {
int angles;
char shape_name[16];
};
typedef struct shape shape_t;
struct container {
char name[32];
shape_t **elements;
int num_elts;
};
typedef struct container container_t;

shape_t triangle = {
.angles = 3,
.shape_name = { "Triangle" }
};
shape_t rectangle = {
.angles = 4,
.shape_name = { "Rectangle" }
};

container_t c = {
.name = { "Case" },
.elements = (shape_t *[]) {
&triangle,
&rectangle,
},
.num_elts = 2,
};

int main(void) {
return 0;
}

请注意对指向 shape_t 元素的指针数组使用复合文字。

关于c - 初始化指向结构的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671122/

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