我说我有一个 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", ¬e[0]);
while ( !feof( ifile)) {
i++;
note = (double *) realloc( note, i * sizeof( double));
fscanf( ifile, "%lf", ¬e[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]
。
检查所有使用的库函数的返回值也是一个好习惯,例如open
、new
、realloc
和 scanf
。
这些问题的快速修复可能是以下代码段。请注意,我使用了与您相同的重新分配策略(每次),但正如@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/