【发布时间】:2013-05-06 04:36:14
【问题描述】:
我的程序需要从输入文件中读取值(整数和浮点数)。一行中有很多值,用制表符分隔,文件中有很多行。我计划逐行读取整个文件,解析每一行并将整个内容存储到由二维静态数组组成的结构中。然后,当整个内容存储在内存中时,我会进行计算,将结果填充到另一个结构中,最后将该结构的内容转储到输出文件中。当然它不起作用,尝试运行程序时出现分段错误错误。
这就是我定义输入结构的方式:
#define sim_spectrum_constant 122
#define real_spectrum_constant 181
#define num_days 365
struct spectrum {
int year[sim_spectrum_constant][num_days];
int month[sim_spectrum_constant][num_days];
int day[sim_spectrum_constant][num_days];
int hour[sim_spectrum_constant][num_days];
int minute[sim_spectrum_constant][num_days];
int second[sim_spectrum_constant][num_days];
float wavelength[sim_spectrum_constant][num_days];
float irr_total[sim_spectrum_constant][num_days];
float irr_direct[sim_spectrum_constant][num_days];
float irr_diffuse[sim_spectrum_constant][num_days];
};
struct spectrum pS;
这就是我初始化数组的方式:
// initialization
for (i=0; i<sim_spectrum_constant; i++) {
for (j=0; j<num_days; i++) {
pS.year[i][j] = 0;
pS.month[i][j] = 0;
pS.day[i][j] = 0;
pS.hour[i][j] = 0;
pS.minute[i][j] = 0;
pS.second[i][j] = 0;
pS.wavelength[i][j] = 0.;
pS.irr_total[i][j] = 0.;
pS.irr_direct[i][j] = 0.;
pS.irr_diffuse[i][j] = 0.;
}
}
这就是我从输入文件中读取值的方式:
// determining how many simulated spectrums are provided in the file + reading spectrums into the array
row = 0;
n = 0;
if (fgets(line, sizeof(line), pInput_spektrum) == NULL) {
printf ("****Simulated spectrum doesn't contain any entries!! -- %s\nPress <enter> to exit...\n", strerror(errno));
getchar();
exit(-1);
}
while(fgets(line, sizeof(line), pInput_spektrum) != NULL) {
result=sscanf(line, "%i %i %i %i %i %i %f %f %f %f", pS.year[row][n], pS.month[row][n], pS.day[row][n], pS.hour[row][n], pS.minute[row][n], pS.second[row][n], pS.wavelength[row][n], pS.irr_total[row][n], pS.irr_direct[row][n], pS.irr_diffuse[row][n]);
row ++;
if (row == sim_spectrum_constant) {
n ++;
last_row = row;
row = 0;
}
}
我的想法、实施或两者都失败了吗?什么导致分段错误?
谢谢!
【问题讨论】:
-
这些数组是否在某处初始化?
-
不,这是强制性的吗?这是我十年来的第一个 C 程序,抱歉 :(
-
我刚刚添加了初始化并重新编译,似乎仍然是同样的问题。我已经更新了上面的 init 是如何完成的。
-
能否调试一下,知道错误出现在哪一行?
-
我确实尝试过,但是调试从未通过程序运行。我几乎立即收到警告消息,即“程序中引发了访问冲突(分段错误)”。之后调试似乎无法通过程序。我还尝试在整个程序中设置控制 printfs,每隔几行打印增量数字,以便能够更准确地定位问题所在。但是,当我运行程序时,甚至没有看到第一个打印输出——这意味着程序实际上根本没有启动?