[英]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.