2010-07-18 3 views
1

다음 코드와 비슷한 작업을하고 있습니다. 나는 이미 AddtoStructFunction()을 통해 mystruct을 한 번 채웠다. 이제는 새로운 항목을 모두 mystruct에 추가하지 않고도 mystruct에 직접 추가하고 mystruct에 삽입 할 새 키가 포함 된 g_hash_table 전체를 반복하여 다시 작성해야합니다.c realloc struct -g_hash_table

이 작업을 수행하는 좋은 방법은 무엇입니까? 각 새 항목을 다시 할당 하시겠습니까?

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

realloc 함수를 사용하여 구조체 포인터의 배열을 다시 할당 할 수 있습니다. 성공할 경우 기존 데이터를 새 배열에 복사합니다 (mystruct 인스턴스에 20 개의 포인터 배열이 있고 realloc 배열에 30이 포함될 경우 첫 번째 20은 원래 배열과 같습니다).

GLib를 사용하고 있으므로 mystruct**이 아닌 GArray으로 간주 할 수 있습니다. 그것은 당신을 위해 재 할당을 처리합니다.