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

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

谢谢!

4

2 回答 2

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   
于 2012-10-23T19:38:53.327 回答
2

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

DictionaryArray myArray({ /* some list */ });
于 2012-10-23T19:36:54.103 回答