我正在尝试将char数组设置为结构,但是当我尝试将其打印出来时。我遇到了分段错误。我做错了什么?
typedef struct buckets_{
char *key;
data *next;
}buckets;
typedef struct hash_table_ {
int (*hash_func)(char *);
int (*comp_func)(void*, void*);
buckets **buckets_array;
} hash_table, *Phash_table;
table_p -> buckets_array[0] = malloc(sizeof(buckets));
table_p -> buckets_array[1] = malloc(sizeof(buckets));
char word2[5] = "Hieo";
table_p -> buckets_array[1] -> key = malloc(sizeof(word2));
table_p -> buckets_array[1] -> key = word2;
printf("%s",table_p -> buckets_array[i] -> key); /*Getting segmitation falut here*/
Opp忘了提到我有一个分配数组的功能。假设我分配了数组。
答案 0 :(得分:1)
这是我能看到的:
buckets_array
。key
分配了内存,但随后通过分配key = word2
立即泄露了内存。我想您打算使用strcpy
或memcpy
。i
的可能未初始化的变量。我想这就是问题所在。答案 1 :(得分:0)
您永远不会初始化bucket_array
,因此它是无效指针。您需要先将其初始化:
table_p->buckets_array = malloc(number_of_elements * sizeof(buckets*));
// now that the top level pointer is initialize
// you can initialize each element that it points to.