我的问题与 GLib、C 编程有关。 当我初始化结构 GHashtable 时。
struct _GHashTable
{
gint size;
gint mod;
guint mask;
gint nnodes;
gint noccupied; /* nnodes + tombstones */
gpointer *keys;
guint *hashes;
gpointer *values;
GHashFunc hash_func;
GEqualFunc key_equal_func;
gint ref_count;
GDestroyNotify key_destroy_func;
GDestroyNotify value_destroy_func;
};
GHashTable *hash_table;
hash_table = (GHashTable *)malloc(sizeof(GHashTable));
在我的哈希表中,我有三个数组来存储键、值和哈希值。
gpointer *keys;
guint *hashes;
gpointer *values;
我在初始化函数中初始化了那些数组:
hash_table->keys = malloc(sizeof(gpointer) * hash_table->size);
hash_table->values = hash_table->keys;
hash_table->hashes = malloc(sizeof(guint) * hash_table->size);
我的问题是当我在分配内存后显示 hash_tables 时,我发现值数组中存储了一个数字。
[0] key: (null) hash: 0 values: (null)
[1] key: (null) hash: 0 values: (null)
// Where is the 64273 comes from? Why other array are
// initialized as 0 or null. Only this index is initialized like that?
[2] key: (null) hash: 64273 values: (null)
[3] key: (null) hash: 0 values: (null)
[4] key: (null) hash: 0 values: (null)
[5] key: (null) hash: 0 values: (null)
[6] key: (null) hash: 0 values: (null)
[7] key: (null) hash: 0 values: (null)
我是否必须手动初始化键、值和哈希数组,在为它们分配内存后将值分配为 0 或 NULL?
不赋0或NULL,会出现一些随机数或垃圾数吗?
谢谢。
最佳答案
你不应该自己初始化一个GHashTable
。 GHashTable
结构在公共(public) header 中不完整,是私有(private) API。它可以更改,恕不另行通知。你应该调用 g_hash_table_new
(或 g_hash_table_new_full
),这将分配内存并正确初始化哈希表。
关于c - 在 C 中初始化结构体 GHashTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574578/