【发布时间】:2016-07-24 17:31:49
【问题描述】:
说我有一个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[1] 分配任何值。
-
@SergeBallesta 练习指定不要使用大小有限的向量。
-
@SergeBallesta "不相关,但重新分配每个新值是一种反模式。"在编码犯罪领域,为每次循环迭代调用
realloc()是尽可能轻微的冒犯。而且我什至不确定它是否应该被视为一个反模式——这样的代码比realloc()的大块代码更简单、更容易编写和维护。它只是更慢。也许吧。
标签: c algorithm file pointers vector