簡體   English   中英

如何創建靜態分配的動態大小的數組?

[英]How can I create a statically allocated dynamically sized array?

typedef struct DictionaryEntry_s {
    char *key;
    char *value;
} DictionaryEntry;

typedef struct Dictionary_s {
    char *name;
    DictionaryEntry values[0];
} Dictionary;

//How can I do the following:
Dictionary myDictionary[] = { 
    {"synonyms",
        {"good", "cool"},
        {"bad", "evil"},
        {"awesome", "me"},
        {"like", "love"}, //etc....
        {0} //terminator
    },
    {"antonyms",
        {"good", "evil"},
        {"bad", "good"},
        {"awesome", "not me"}, ///...etc
        {0} //terminator
    },
    {0} //terminator
};

正如您在代碼中看到的那樣,我想創建一個靜態分配但動態大小的數組。 我知道如何遍歷數據,只是編譯器在聲明中bar倒了。 當我在尋找C解決方案時,除了C ++外,還有積分。

謝謝!

C解決方案需要額外的變量來定義內部數組:

typedef struct DictionaryEntry_s {
    char *key;
    char *value;
} DictionaryEntry;

typedef struct Dictionary_s {
    char *name;
    DictionaryEntry* values;
} Dictionary;

//How can I do the following:
DictionaryEntry myDictionary0[] = {
        {"good", "cool"},
        {"bad", "evil"},
        {"awesome", "me"},
        {"like", "love"}, //etc....
        {0} //terminator
};
Dictionary myDictionary[] = { 
    {"synonyms", myDictionary0},
    // ...
    {0} //terminator
}; // <-- semicolon was missing here

C ++解決方案-需要std::vector<> -但是它不是statically分配的,而是動態分配的,並且不需要終結符:

struct DictionaryEntry {
    char *key;
    char *value;
};

struct Dictionary {
    char *name;
    std::vector<DictionaryEntry> values;
};

//How can I do the following:
Dictionary myDictionary[] = { 
    {"synonyms",
      {
        {"good", "cool"},
        {"bad", "evil"},
        {"awesome", "me"},
        {"like", "love"}, //etc....
        {0} //terminator
      } 
    },
    //...
    {0} //terminator
}; // <-- semicolon was missing here   

在C ++ 11中,可以使用初始化程序列表 您可以使用采用其中之一的構造函數定義DictionaryArray類,然后編寫

DictionaryArray myArray({ /* some list */ });

暫無
暫無

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

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