C:使用指针静态初始化复合结构

布利亚科

我有一个嵌套的 C (gcc-11) 结构,它包含一个指向另一个结构的指针数组。我想创建一个这种类型的静态变量并同时对其进行初始化。所有这些都在一个头文件中。原因是它代表了一些属于该头文件的默认值。我不想调用初始化函数来设置它。

以下编译正常:

typedef struct s1_s {
        int a;
        int b;
} s1_t;

typedef struct s2_s {
        int c;
        s1_t *s1s; // but I need this to be **s1s really!
} s2_t;

s2_t *def = &(s2_t){
        .c = 10,
        .s1s = &(s1_t){  
                .a = 100,
                .b = 200 
        } 
};
int main(void){ return 1; }

但我想要一个指针数组:s1_t **s1s,准确地说。这不编译:

typedef struct s1_s {
        int a;
        int b;
} s1_t;

typedef struct s2_s {
        int c;
        s1_t **s1s; // "array" of pointers
} s2_t;

s2_t *def = &(s2_t){
        .c = 10,
        // I want an "array" of 1 *(s1_t*) element
        .s1s = &(s1_t *){{  
                .a = 100,
                .b = 200 
        }} 
};
int main(void){ return 1; }

这些是第一个错误:

warning: braces around scalar initializer
   15 |         .s1s = &(s1_t *){{
error: field name not in record or union initializer
   16 |                 .a = 100,
...
斯坦尼斯尔

只需这样做:

s2_t *def = &(s2_t){
        .c = 10,
        // I want an "array" of 1 *(s1_t*) element
        .s1s = (s1_t*[]){&(s1_t){  
                .a = 100,
                .b = 200 
        }} 
};
  • (s1_t*[])表示复合文字的类型是“指向s1_t的指针数组编译器会自动推断其大小
  • 数组的每个元素都必须是一个指针,因此它被定义为 &(s1_t) { ... }

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章