一次增加一条记录的数组大小——对性能不利,但相对简单:
int InputData(Student **p_array, FILE*fp)
{
Student *temp = 0;
Student data;
int i = 0;
while (fscanf(fp, "%s%d%d%d", data.name, &data.grades[0],
&data.grades[1], &data.grades[2]) == 4)
{
size_t space = ++i * sizeof(Student);
Student *more = (Student *)realloc(temp, ++i * sizeof(Student));
if (more == NULL)
Error_Msg("Memory allocation failed!");
temp = more;
temp[i-1] = data;
}
*p_array = temp;
return i;
}
请注意,在调用 Error_Msg() 之前,您可以(也许应该)free(temp)。请注意,realloc() 不使用 ptr = realloc(ptr, new_size) 习惯用法,因为如果重新分配失败,则会丢失(泄漏)先前分配的内存。
另一种选择——在返回之前缩小分配:
int InputData(Student **p_array, FILE*fp)
{
int i = 1;
Student *temp = (Student *)malloc(sizeof(Student));
if (temp == NULL)
Error_Msg("Memory allocation failed!");
while (fscanf(fp, "%s%d%d%d", temp[i - 1].name, &temp[i - 1].grades[0],
&temp[i - 1].grades[1], &temp[i - 1].grades[2]) == 4)
{
i++;
temp = (Student*)realloc(temp, sizeof(Student)*i);
if (temp == NULL)
Error_Msg("Memory allocation failed!");
}
assert(i > 0);
temp = (Student *)realloc(temp, sizeof(Student) * (i - 1));
*p_array = temp;
return i;
}
我不喜欢这个,因为 temp = realloc(temp, new_size) 成语,但你也可以解决这个问题。