如何创建静态分配的动态大小的数组?

时间:2012-10-23 19:31:15

标签: c++ c memory-management

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
};

正如您在代码中看到的,我想创建一个静态分配但动态大小的数组。我知道如何遍历数据,它只是编译器barfs在声明。虽然我正在寻找一个C解决方案,另外还有C ++的奖励积分。

谢谢!

2 个答案:

答案 0 :(得分:3)

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   

答案 1 :(得分:2)

在C ++ 11中,您可以使用初始化列表。您可以使用构造函数定义DictionaryArray类,其中包含其中一个,然后编写

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