c realloc struct - g_hash_table - PullRequest
       34

c realloc struct - g_hash_table

1 голос
/ 18 июля 2010

Я делаю что-то похожее на следующий код. Я уже прошел через AddtoStructFunction() заполнение mystruct один раз. Теперь я хотел бы добавить каждую новую запись непосредственно к mystruct, не освобождая mystruct, и итерировать заново все g_hash_table, содержащие новые ключи, чтобы вставить их в mystruct ,

Что было бы хорошим способом сделать это? перераспределять каждую новую запись?

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");

1 Ответ

1 голос
/ 18 июля 2010

Вы можете использовать функцию realloc для перераспределения массива указателей структуры.В случае успеха он скопирует существующие данные в новый массив (если у вас есть массив из 20 указателей на mystruct экземпляров и realloc массив, содержащий 30, первые 20 будут такими же, как ваш исходный массив).

Поскольку вы используете GLib, вы также можете рассмотреть GArray вместо простого mystruct**.Он обрабатывает перераспределение для вас.

...