在 C 中取消引用指定结构初始化程序内的指针

一护gyuunyuu

假设我有以下结构

typedef struct foo {
    int    a;
    char **b;
} foo;

这就是我想要做的

char *bar0 = malloc(sizeof *bar0);
char *bar1 = malloc(sizeof *bar1);

foo f = {
    .a    = 4,
    .b    = malloc(2 * sizeof(char *)),
    .b[0] = bar0, // not allowed!
    .b[1] = bar1, // not allowed!
}

GCC 错误,因为array index in non-array initializer.我也尝试过.(*b) = bar0and .(*(b+1)) = bar1,但它们在语法上也无效。

编辑:有没有办法在初始化程序中分配bar0和,而不是使用单独的分配表达式?bar1

伊恩·雅培

有没有办法在初始化程序中分配bar0and ,而不是使用单独的分配表达式?bar1

不,f.b是指向已分配对象的指针(在这种情况下通过调用返回malloc),并且无法使用初始化程序初始化已分配对象。只需删除有问题的指定初始化程序并改用赋值表达式:

char *bar0 = malloc(sizeof *bar0);
char *bar1 = malloc(sizeof *bar1);

foo f = {
    .a    = 4,
    .b    = malloc(2 * sizeof(char *)),
};
f.b[0] = bar0;
f.b[1] = bar1;

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章