简体   繁体   中英

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. 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. Its size is 32 or 64 bits. When you take its address, like &hash->stats , the results is an address that points into the stucture, very close to its end.

The call to memset clears the pointer field itself and the memory after it, that is right after the sturcture. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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