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

标签 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++ 的加分。

谢谢!

最佳答案

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++ - 如何创建静态分配的动态大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13037806/

相关文章:

python - 如何从给定模型中获取 Graph(或 GraphDef)?

c++ - 将 CUDA 分配 char * 到对象的 device_vector

c - 字符串怎么可能是 boolean 值?

c++ - 段错误和内存泄漏

c++ - 错误 : ‘List’ is not a template type

c++ - 为什么调用另一个对象的析构函数?

c++ - 随机数生成器的实现

c++ - 我们如何使用强制转换来允许将字符屏蔽为字符串?

memory-management - CUDA 映射内存是否占用 GPU RAM?

c - 整数数组到 char 指针字符串