在C上分配struct的动态数组

在C上分配动态数组结构.Valgrind发现了这个错误:使用大小为8的未初始化值。在尝试访问struct成员时弹出错误。

有什么方法可以避免这种情况?

void find_rate() { int num_lines = 0; FILE * in; struct record ** data_array; double * distance; struct record user_record; in = open_file(); num_lines = count_lines(in); allocate_struct_array(data_array, num_lines); data_array[0]->community_name[0] = 'h'; // the error is here printf("%c\n", data_array[0]->community_name[0]); fclose(in); } FILE * open_file() { ..... some code to open file return f; } int count_lines(FILE * f) { .... counting lines in file return lines; } 

这是我分配数组的方式:

 void allocate_struct_array(struct record ** array, int length) { int i; array = malloc(length * sizeof(struct record *)); if (!array) { fprintf(stderr, "Could not allocate the array of struct record *\n"); exit(1); } for (i = 0; i < length; i++) { array[i] = malloc( sizeof(struct record) ); if (!array[i]) { fprintf(stderr, "Could not allocate array[%d]\n", i); exit(1); } } } 

因为您将数组的地址传递给函数allocate_struct_array

你需要:

 *array = malloc(length * sizeof(struct record *)); 

在调用函数中,您需要将data_array声明为:

 struct record * data_array; 

并将其地址传递给:

 allocate_struct_array(&data_array, num_lines);