为什么我不能将此指针设置为NULL?

时间:2012-05-02 15:44:03

标签: c pointers structure

我在将结构中的指针设置为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;

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;