简体   繁体   English

指向Struct指针成员的指针

[英]Pointer to Struct pointer member

I have "hash" which is pointer to a struct. 我有“哈希”这是指向结构的指针。 I'm trying to get it's member stats which is also a pointer. 我正在尝试获取它的成员统计信息,这也是一个指针。 I thought I could just do: hash->stats but that appears to return the reference stats struct. 我以为我可以做:hash-> stats,但这似乎返回了引用stats结构。 The "->" should just dereference the variable on the left? “->”应该只是取消引用左侧的变量?

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

If I try this at this point: 如果我现在尝试这样做:

struct statistics *st = hash->stats;

I get: 我得到:

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

Your line of code 您的代码行

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

is plain wrong. 是完全错误的。 The hash->stats is a pointer. hash->stats是一个指针。 Its size is 32 or 64 bits. 它的大小是32或64位。 When you take its address, like &hash->stats , the results is an address that points into the stucture, very close to its end. 当您获取其地址(如&hash->stats ,结果就是指向该结构的地址,该地址非常接近其末端。

The call to memset clears the pointer field itself and the memory after it, that is right after the sturcture. memset的调用将清除指针字段本身及其后的内存,即在结构之后的内存。 You corrupt some memory in the heap. 您破坏了堆中的某些内存。 This will result either in undefined behavior or a crash. 这将导致不确定的行为或崩溃。 You should write something like: 您应该编写如下内容:

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

This will init your data. 这将初始化您的数据。 Plus you need to free your memory when you are done with your data structure. 另外,完成数据结构后,您需要释放内存。

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

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