1

我正在做类似于以下代码的事情。我已经完成了一次AddtoStructFunction()填充mystruct。现在,我想做的是将每个新条目直接附加mystruct到. mystructg_hash_tablemystruct

这样做的好方法是什么?重新分配每个新条目?

void InsertFunction(GHashTable *hash, char *str) {
    g_hash_table_insert(hash, str, "Richmond");
}

void AddtoStructFunction(struct dastruct **mystruct) {
    // initial fill with all elements of g_hash_table_size(g_hash_table) at the time AddtoStructFunction is called.
    mystruct = (struct dastruct **)malloc(sizeof(struct dastruct *)*g_hash_table_size(g_hash_table));
    g_hash_table_iter_init(&iter, g_hash_table);
    while (g_hash_table_iter_next(&iter, &key_, (gpointer) &val)) {
        mystruct[i] = (struct dastruct *)malloc(sizeof (struct dastruct));
        mystruct[i]->myKey = (gchar *) key_;
        i++;
    }
}

void AddExtraOnes(struct dastruct **mystruct, char *string) {
    // realloc mystruct here?
    // each time I call AddExtraOnes, I'd like to append them to mystruct
    mystruct[?]->myKey = string;
}

int i;
for(i = 0; i < 100000, i++){
    InsertFunction(g_hash_table, "RandomStrings");
}
AddtoStructFunction(mystruct);
...
// do this n times
AddExtraOnes(mystruct, "Boston");
4

1 回答 1

1

您可以使用该realloc函数重新分配结构指针数组。如果成功,它会将现有数据复制到新数组(如果您有一个包含 20 个指向mystruct实例的指针的数组并且realloc该数组包含 30 个,则前 20 个将与您的原始数组相同)。

由于您使用的是 GLib,因此您可能还会考虑GArray使用普通的mystruct**. 它为您处理重新分配。

于 2010-07-18T01:39:35.460 回答