代码之家  ›  专栏  ›  技术社区  ›  Christine Harper

尝试从文件读入2D数组时出现分段错误

  •  -1
  • Christine Harper  · 技术社区  · 7 年前

    以下是我的变量:

    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;
    

    这是我的分配。

    mazearray = (char**) malloc(sizeof(char*)*rowsize);
    
        for(i =0; i<rowsize; ++i)
        {
                mazearray[i]= (char*)malloc(sizeof(char)*colsize);
        }
    

    这是我试图从文件中读取并解析信息。我首先尝试读入3行字符串,其中包含有关迷宫的信息(数组大小、入口、出口等),然后尝试用底部的for循环填充2d数组。

    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);
    

    同样,任何方向都会有所帮助。谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   JeremyP    7 年前

    rowSize colSize 均为零:

    mazearray = (char**) malloc(sizeof(char*)*rowsize);
    
    for(i =0; i<rowsize; ++i)
    {
            mazearray[i]= (char*)malloc(sizeof(char)*colsize);
    }
    

    没有字节将分配给 mazearray . 这个 for 循环将不执行任何次。

    我看到你在读 行大小 从…起 stdin 但在阅读了它们之后,您在任何时候都不会使用新的大小分配数组。