繁体   English   中英

指向Struct指针成员的指针

[英]Pointer to Struct pointer member

我有“哈希”这是指向结构的指针。 我正在尝试获取它的成员统计信息,这也是一个指针。 我以为我可以做:hash-> stats,但这似乎返回了引用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'

您的代码行

 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));

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM