I'm doing something similar to the following code. I have already gone through AddtoStructFunction()
filling mystruct
once. Now, what I would like to do is to append every new entry directly to the mystruct
without having to free mystruct
and iterate over again the whole g_hash_table
containing the new key(s) to insert them into mystruct
.
What would be a good way of doing this? realloc each new entry?
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");
You can use the realloc
function to reallocate your array of struct pointers. It will copy the existing data to the new array if it succeeds (if you have an array of 20 pointers to mystruct
instances and realloc
the array to contain 30, the first 20 will be the same as your original array).
Since you're using GLib, you might also consider GArray
rather than a plain mystruct**
. It handles re-allocation for you.
精彩评论