簡體   English   中英

C:結構數組(包含一個 int 和另一個結構的另一個數組)

[英]C : array of struct (which holds an int and another array of another struct)

struct dataStruct {     const char* s;     int num; }; 

struct Final_struct {     int n;     dataStruct a[]; }; 

現在,當我嘗試按如下方式初始化 Final_struct 時,就會出現問題:

const Final_struct Example[]= {
                                {100, { {"age", 20}, {"iq", 120}, {"bmi",26} } },
                                {100, { {"age", 36}, {"iq", 145}, {"bmi",22} }}
};

這是一個 c 代碼,當我嘗試編譯時,它給出了編譯器錯誤:

Fields of the object can not have arrrays of size 0

有什么建議么?

謝謝你。

dataStruct a[]將結構的成員定義為大小0的數組。 這實際上是沒有用的。 您需要在struct的定義中指定其大小,因為編譯器需要提前知道整個struct的大小。

或者,您可以簡單地將字段聲明為dataStruct *a ,然后數組本身將不包含在struct中。

如果這是 C,什么是string 為什么你期望能夠從看起來像其他變量的東西初始化它?

嘗試const char * for s ,並從帶引號的字符串文字初始化。

您是否忘記了字符串上的引號?

“年齡”

您是否嘗試在字符串常量周圍加上雙引號?

有什么建議么?

嘗試:

/* note the explicit array size for a[] */
struct Final_struct {     int n;     struct dataStruct a[3]; };

在名為 Final_struct 的結構中聲明的數組“a”應該具有大小。 在不知道該變量的大小的情況下,編譯器無法為該變量分配 memory。 所以你應該先分配大小......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM