初始化结构的指针数组

纽力克

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

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 sturcts的指针数组,但是此代码无法编译:

 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?那么正确的初始化语法是什么?

乔纳森·勒夫勒(Jonathan Leffler)

你快到了;您只需要确保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元素的指针数组中使用了复合文字

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档