0

我在将结构中的指针设置为 NULL 时遇到了一些问题。我遇到了分段错误。是什么原因造成的,我该如何解决?

typedef struct data_{
  void *data;
  struct data_ *next;
}data_el;

typedef struct buckets_{
  char *key;
  data_el *head_data_p;
}buckets;

typedef struct hash_table_ {
  /* structure definition goes here */
  int (*hash_func)(char *);
  int (*comp_func)(void*, void*);
  buckets **buckets_array;
} hash_table, *Phash_table;

int i,size;
size = 10;

table_p -> buckets_array = (buckets **)malloc(sizeof(buckets)*(size+1));

for(i = 0; i < size; i++){
/*Getting segmitation falut here*/
table_p -> buckets_array[i] -> key = NULL;
table_p -> buckets_array[i] -> head_data_p = NULL;
4

2 回答 2

2

因为你没有初始化buckets_array. 所以指针还没有指向任何东西,当你尝试修改它们指向的东西时你会得到一个错误。

您需要初始化指针数组以及每个单独的指针:

table_p -> buckets_array = malloc(sizeof(buckets *) * (size+1));

for(i = 0; i < size; i++) {
    table_p -> buckets_array[i] = malloc(sizeof(bucket));
    table_p -> buckets_array[i] -> key = NULL;
    table_p -> buckets_array[i] -> head_data_p = NULL;
}
于 2012-05-02T15:48:26.750 回答
1

你应该更换:

buckets **buckets_array;

和:

buckets *buckets_array;

和:

(buckets **)malloc(sizeof(buckets)*(size+1));

和:

(buckets *)malloc(sizeof(buckets)*(size+1));

并且:

table_p -> buckets_array[i] -> key = NULL;
table_p -> buckets_array[i] -> head_data_p = NULL;

和:

table_p -> buckets_array[i] . key = NULL;
table_p -> buckets_array[i] . head_data_p = NULL;
于 2012-05-02T15:47:55.927 回答