我有一個嵌套的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; //"陣列 "的指標。
} 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 *) {{
錯誤:欄位名不在記錄或union初始化器中
16 | .a = 100,
...
uj5u.com熱心網友回復:
只要這樣做:
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) { ... }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315436.html
標籤:
