c - 如何从未指定的文件大小中读取值并将它们动态存储在 C 中的 vector 中?

标签 c algorithm file pointers vector

我说我有一个 numbers.txt 文件,其大小未指定为 double 数字。

我需要将这些值动态地存储在一个double *note 指针中供以后使用。

我尝试了以下代码,但它给出了核心转储:

FILE *ifile = fopen("numbers.txt", "r");
double *note;
int i = 1; 

note = (double *) malloc( i * sizeof( double));
fscanf( ifile, "%lf", &note[0]); 

while ( !feof( ifile)) {
      i++;
      note = (double *) realloc( note, i * sizeof( double));
      fscanf( ifile, "%lf", &note[i]);
}       

for (n=0; n < i; n++) {
     printf( "%lf\n", note[i]);
}

最佳答案

每次使用 note[i] 时,您的代码都会越界访问数组。

在 ( wrong ) while 循环中,它总是超过最后一个元素(例如,在第一次迭代中 i 变为 2,足够的空间容纳两个 double已分配,但您访问的是 note[2],这是第三个)。

打印时,您使用 n 作为递增循环索引,但总是打印 note[i] 而不是 note[n]

检查所有使用的库函数的返回值也是一个好习惯,例如opennewreallocscanf

这些问题的快速修复可能是以下代码段。请注意,我使用了与您相同的重新分配策略(每次),但正如@Serge Ballesta 指出的那样,这可能效率低下。例如,查看@Jean-François Fabre 答案中显示的替代方案。

#include <stdio.h>
#include <stdlib.h>

int main() {
    double value,
           *note = NULL,
           *newptr = NULL;

    int i,
        size = 0;

    char file_name[] = "numbers.txt";
    FILE *ifile = fopen(file_name, "r");
    if ( !ifile ) {
        fprintf(stderr, "Error while opening file %s.\n", file_name);
        exit(EXIT_FAILURE);
    }

    while ( fscanf(ifile, "%lf", &value) == 1 ) {
        size++;
        newptr = realloc(note, size * sizeof(double));
        if ( !newptr ) {
            fprintf(stderr, "Error while reallocating memory.\n");
            free(note);
            exit(EXIT_FAILURE);
        }
        note = newptr;
        note[size - 1] = value;
    }       

    for (i=0; i < size; i++) {
        printf( "%lf\n", note[i]);
    }

    free(note);     // <-- don't leak memory!
    fclose(ifile);
    return EXIT_SUCCESS;
}

关于c - 如何从未指定的文件大小中读取值并将它们动态存储在 C 中的 vector 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38554803/

相关文章:

c - 乘以 sizeof(char) 不同于仅乘以 char 的大小

c - struct中 "typedef"是什么意思

c++ - 给定一个单词和一段文本,我们需要返回出现的字谜

linux - 在 ramdisk 上缓存 - 查找要删除的最旧文件

javascript - 动态输入文件中没有加载数据

c - 获取包含链接列表的功能以在C中正常工作

C++ 预期类型说明符错误

algorithm - 如果图中有循环,我们可以应用维特比算法吗?

python - 如何使用三次或更高次的多项式曲面回归来拟合一组 3D 数据点?

c - 如何获取每行中的字符数?