如何从文件中读取未知数量的浮点数?

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)

如果它太小,我怎么能动态改变数组的大小呢?

cni*_*tar 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);
    /* ... */
}
Run Code Online (Sandbox Code Playgroud)
  • 您应该尝试覆盖大多数输入的初始大小,而不需要太多内存
  • 您可以尝试不同的realloc策略,将大小加倍只是一个
  • 你或许应该检查的结果mallocrealloc