0

我有“哈希”,它是指向结构的指针。我正在尝试获取它的成员统计信息,这也是一个指针。我以为我可以这样做: hash->stats 但这似乎返回了参考统计数据结构。“->”应该只是取消引用左侧的变量吗?

struct statistics {
    unsigned long long count;   
   ...
};

struct hashtable {
    GHashTable * singleton; //Single Hash Table to Store Addresses
    struct statistics *stats;   //Statistics Table
};

    GHashTable *ghash = g_hash_table_new(NULL, NULL);
    struct hashtable *hash = (struct hashtable *) malloc(sizeof(struct hashtable));

//Works but why isn't hash->stats ok?
    memset(&hash->stats, 0, sizeof(struct statistics));

如果我此时尝试这个:

struct statistics *st = hash->stats;

我得到:

incompatible types when initializing type 'struct statistics *' using type 'struct 
     statistics'
4

1 回答 1

3

你的代码行

 memset(&hash->stats, 0, sizeof(struct statistics));

是完全错误的。是hash->stats一个指针。它的大小是 32 或 64 位。当您获取它的地址时,例如&hash->stats,结果是一个指向结构的地址,非常接近其末端。

调用memset清除指针字段本身和它之后的内存,即在结构之后。您破坏了堆中的一些内存。这将导致未定义的行为或崩溃。你应该写这样的东西:

   struct hashtable *hash = (struct hashtable*)malloc(sizeof(struct hashtable));
   struct statistics *stts = (struct statistics*)malloc(sizeof(struct statistics));

   hash->stats = stts;
   memset(hash->stats, 0, sizeof(struct statistics));

这将初始化您的数据。另外,当您完成数据结构时,您需要释放内存。

于 2012-09-24T06:38:11.777 回答