1

我正在尝试将 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 忘了提到我有一个分配数组的函数。假设我分配了数组。

4

2 回答 2

1

这是我能看到的:

  1. 你没有分配buckets_array
  2. 您为 分配了内存key,但随后通过分配立即泄漏key = word2。我猜你的意思是使用strcpyor memcpy
  3. 您使用了一个可能未初始化的变量,名为i. 我想这就是问题所在。
于 2012-05-02T00:36:28.497 回答
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.
于 2012-05-02T00:34:26.490 回答