在C上分配結構的動態數組Valgrind發現此錯誤:使用大小爲8的未初始化值。嘗試訪問結構成員時彈出錯誤。在C上分配結構的動態數組。
避免這種情況的方法是什麼?
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);
}
}
}
其結構錯誤?你還可以添加valgrind輸出嗎? – IanNorton
你可以粘貼結構記錄的定義嗎? – Louis