[英]segmentation fault while trying to read in from file to a 2D array
I am getting a segmentation fault while trying to read from a file into a 2D dynamic array.尝试从文件读取到二维动态数组时出现分段错误。 I know this is a little vague of a question, but this being my first C code, I haven't been able to trace out what the problem is.我知道这是一个有点含糊的问题,但这是我的第一个 C 代码,我一直无法找出问题所在。 Any direction will be appreciated.任何方向将不胜感激。 These are my variables:这些是我的变量:
int i;
int rowsize=0;
int colsize=0;
int colenter=0;
int rowenter=0;
int colexit=0;
int rowexit=0;
char sizestring[20];
char enterstring[20];
char exitstring[20];
int line=0;
int j;
int k;
char**mazearray;
FILE*file;
And this is my allocation.这是我的分配。
mazearray = (char**) malloc(sizeof(char*)*rowsize);
for(i =0; i<rowsize; ++i)
{
mazearray[i]= (char*)malloc(sizeof(char)*colsize);
}
And this is me trying to read from a file and parse the information.这是我试图从文件中读取并解析信息。 I first try to read in 3 lines of strings which contain the information about a maze (Array size, enterance, exit etc.) and then try to fill out the 2d array with the for loop at the bottom.我首先尝试读入 3 行包含迷宫信息(数组大小、进入、退出等)的字符串,然后尝试使用底部的 for 循环填充二维数组。
file = fopen(argv[1],"r");
if (!file)
{
printf("The file is not connected/n");
}
while (!feof(file))
{
while(line<3)
{
if(line==0)
{
fgets(sizestring,20,file);
sscanf(sizestring,"%d,%d", &colsize, &rowsize);
line++;
}
else if(line ==1)
{
fgets(enterstring,20,file);
sscanf(enterstring,"%d,%d",&colenter, &rowenter);
line++;
}
else if(line ==2)
{
fgets(exitstring,20,file);
sscanf(exitstring, "%d,%d", &colexit, &rowexit);
line++;
}
}
for(j=0; j<rowsize; j++)
{
for(k=0; k<colsize; k++)
{
fscanf(file,"%c",&mazearray[j][k]);
}
}
}
fclose(file);
Again any direction will help.同样,任何方向都会有所帮助。 Thanks谢谢
rowSize
and colSize
are both zero: rowSize
和colSize
都为零:
mazearray = (char**) malloc(sizeof(char*)*rowsize);
for(i =0; i<rowsize; ++i)
{
mazearray[i]= (char*)malloc(sizeof(char)*colsize);
}
No bytes will be allocated to mazearray
.不会为mazearray
分配任何字节。 The for
loop will be executed no times. for
循环不会被执行。
I see you read in rowSize
and colSize
from stdin
but having read them, you do not allocate your arrays at any point with the new sizes.我看到您从stdin
读取了rowSize
和colSize
,但是在读取它们之后,您不会在任何时候使用新大小分配数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.