- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在做类似于以下代码的事情。我已经完成了 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");
最佳答案
您可以使用realloc
函数重新分配您的结构指针数组。如果成功,它会将现有数据复制到新数组(如果您有一个包含 20 个指向 mystruct
实例的指针的数组,并且 realloc
数组包含 30 个,前 20 个将与您的原始数组相同)。
由于您使用的是 GLib,您可能还会考虑使用 GArray
而不是普通的 mystruct**
。它为您处理重新分配。
关于c realloc 结构 - g_hash_table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3273949/
g_hash_table_lookup 和 g_hash_table_insert 是线程安全的吗?我可以使用这样的代码吗: dict = g_hash_table_new(); for (i = 0
我正在做类似于以下代码的事情。我已经完成了 AddtoStructFunction() 填充 mystruct 一次。现在,我想做的是将每个新条目直接附加到 mystruct 而不必释放 mystru
我在 C 中有一些代码,我想在其中使用 int 作为键和 gnome 哈希表中的值。但如果我写: GHashTable* table = g_hash_table_new(g_direct_hash,
我是一名优秀的程序员,十分优秀!