假设我有以下结构
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) = bar0
and .(*(b+1)) = bar1
,但它们在语法上也无效。
编辑:有没有办法在初始化程序中分配bar0
和,而不是使用单独的分配表达式?bar1
有没有办法在初始化程序中分配
bar0
and ,而不是使用单独的分配表达式?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] 删除。
我来说两句