我的程序需要从输入文件中读取值(整数和浮点数)。一行中有很多值,用制表符分隔,文件中有很多行。我计划逐行读取整个文件,解析每一行并将整个内容存储到由二维静态数组组成的结构中。然后,当整个内容存储在内存中时,我会进行计算,将结果填充到另一个结构中,最后将该结构的内容转储到输出文件中。当然它不起作用,尝试运行程序时出现分段错误错误。
这就是我定义输入结构的方式:
#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;
}
}
我的想法、实施或两者都失败了吗?是什么导致分段错误?
谢谢!