2010-07-18 5 views
1

Je fais quelque chose de similaire au code suivant. Je suis déjà passé à AddtoStructFunction() en remplissant mystruct une fois. Maintenant, ce que je voudrais faire est d'ajouter chaque nouvelle entrée directement au mystruct sans avoir à libérer mystruct et itérer à nouveau l'ensemble g_hash_table contenant la nouvelle clé (s) pour les insérer dans mystruct.c realloc struct - g_hash_table

Quelle serait une bonne façon de procéder? realloc chaque nouvelle entrée?

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

Répondre

1

Vous pouvez utiliser la fonction realloc pour réallouer votre tableau de pointeurs struct. Il copiera les données existantes dans la nouvelle matrice si elle réussit (si vous avez un tableau de 20 pointeurs vers mystruct instances et realloc le tableau pour contenir 30, les 20 premiers seront les mêmes que votre tableau original).

Puisque vous utilisez GLib, vous pouvez également considérer GArray plutôt qu'un mystruct**. Il gère la réallocation pour vous.