我有一个程序,我需要从文件中读取浮点数。每行是一个浮点数。问题是这个文件可能非常大
float tab[1000];
f = fopen ("data.txt", "r");
i=0;
while (feof(f) == 0) {
fscanf (f, "%f\n", &tab[i]);
i++;
}
如果它太小,我如何更改动态数组的大小?
答案 0 :(得分:6)
如果需要的话,只需从合适的尺码malloc
开始,然后realloc
开始。
double *tab;
int num = 1000;
tab = malloc(num * sizeof *tab);
while (..) {
if (i >= num)
num *= 2;
tab = realloc(tab, num * sizeof *tab);
/* ... */
}
malloc
和realloc