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
is plain wrong. The
hash->statsis 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
memsetclears 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:This will init your data. Plus you need to free your memory when you are done with your data structure.