我正在尝试从一个文件中读取值,然后在一些操作后写入另一个文件。这里面临一个小问题,因为我也在尝试将值保存在二维数组中并显示它。我的文件读取和文件写入显示正确的结果,但我的程序在显示矩阵部分时抛出异常。
#include <stdio.h>
#include <ctype.h>
#ifndef NULL
#define NULL ((void *) 0)
#endif
int main(void)
{
FILE *file = NULL; //for file read
FILE *fptr = NULL; //for file write
int mat[182][274];
// code to read and display number from file
// open file for reading
file = fopen("file.txt", "r");
fptr = fopen("file1.txt", "w");
int i = 0,j=0;
fscanf (file, "%d", &i);
while (!feof (file))
{
symbol = fgetc(file);
if (symbol == '\n' || feof(file))
{
fprintf (fptr,"\n");
printf("\n");
}
else{
j=255-i;
mat[i][j]=j;
fprintf (fptr,"%d ", j);
fprintf (fptr," ");
printf ("%d ", j);
}
fscanf (file, "%d", &i);
}
fclose (file);
fclose (fptr);
//Facing issue in this part
int k;
int l;
for (k=0;k<=182;k++)
{
for(l=0;l<=274;l++)
{
printf("%d ", mat[k][l]);
}
}
return 0;
}
最佳答案
C 中的数组从 0
开始结束于 (array_size - 1)
.
当您访问阵列外部的内存时,您很可能会遇到段错误。
要解决此问题,请更改以下行:
for (k=0;k<182;k++)
{
for(l=0;l<274;l++)
{
printf("%d ", mat[k][l]);
}
}
请注意,我更改了 <=
中的关系运算符和 >=
至 <
和 >
, 分别。
除此之外,您可能需要完全初始化您的阵列。如果数组未初始化,可能会打印奇数。 (@Weather Vane)。
但是,为了最好地确定是否是这种情况,我们需要 file.txt
和 file1.txt
.
关于c - 从文件中读取值并将其存储在二维矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53935788/