Reputation: 9502
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'
Upvotes: 0
Views: 2143
Reputation: 10557
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.
Upvotes: 3