c realloc结构-g_哈希表
我正在执行类似于以下代码的操作。我已经完成了c realloc结构-g_哈希表,c,glib,realloc,C,Glib,Realloc,我正在执行类似于以下代码的操作。我已经完成了AddtoStructFunction()fillingmystruct一次。现在,我想做的是将每个新条目直接附加到mystruct,而不必释放mystruct,并再次迭代包含新键的整个g\u哈希表,将它们插入mystruct 这样做的好方法是什么?每个新条目都有吗 void InsertFunction(GHashTable *hash, char *str) { g_hash_table_insert(hash, str, "Richmon
AddtoStructFunction()
fillingmystruct
一次。现在,我想做的是将每个新条目直接附加到mystruct
,而不必释放mystruct
,并再次迭代包含新键的整个g\u哈希表
,将它们插入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");
void InsertFunction(GHashTable*hash,char*str){
g_hash_table_insert(hash,str,“Richmond”);
}
void AddtoStructFunction(struct dastruct**mystruct){
//在调用AddtoStructFunction时,使用g_哈希表大小(g_哈希表)的所有元素进行初始填充。
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){
//真的吗?
//每次调用addExtraOne时,我都希望将它们附加到mystruct中
mystruct[?]->myKey=string;
}
int i;
对于(i=0;i<100000,i++){
插入函数(g_哈希_表,“随机字符串”);
}
AddtoStructFunction(mystruct);
...
//这样做n次
附录(mystruct,波士顿);
您可以使用realloc
函数重新分配结构指针数组。如果成功,它会将现有数据复制到新数组(如果您有一个指向mystruct
实例的20个指针的数组,并且realloc
该数组包含30个指针,那么前20个指针将与原始数组相同)
既然你在使用GLib,你也可以考虑<代码> GArray <代码>,而不是一个简单的<代码> MyStult**/Cord>。它为您处理重新分配。
您可以使用realloc
函数重新分配结构指针数组。如果成功,它会将现有数据复制到新数组(如果您有一个指向mystruct
实例的20个指针的数组,并且realloc
该数组包含30个指针,那么前20个指针将与原始数组相同)
既然你在使用GLib,你也可以考虑<代码> GArray <代码>,而不是一个简单的<代码> MyStult**/Cord>。它为您处理重新分配