cie*_*bor 0 c arrays floating-point numbers file
可能重复:
C动态增长的数组
我有一个程序,我需要从文件中读取浮点数.每行是一个浮点数.问题是这个文件可能非常大
float tab[1000];
f = fopen ("data.txt", "r");
i=0;
while (feof(f) == 0) {
fscanf (f, "%f\n", &tab[i]);
i++;
}
Run Code Online (Sandbox Code Playgroud)
如果它太小,我怎么能动态改变数组的大小呢?
只需从合适的尺寸开始malloc,然后realloc在需要时随身携带.
double *tab;
int num = 1000;
tab = malloc(num * sizeof *tab);
while (..) {
if (i >= num)
num *= 2;
tab = realloc(tab, num * sizeof *tab);
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
malloc和realloc