C:从文件读取时出现分段错误

时间:2015-04-01 02:41:30

标签: c linux segmentation-fault

我最近开始研究这个项目,而且我在将某些内容读入全局变量时遇到了麻烦。这是pthreads的练习,这就是我首先使用全局变量的原因。该程序应该从一个表示已解决的数独谜题的文件中读取数字,文本文件将被格式化为9个数字字符,后跟一个新行,共9次。我已经确定,在运行此程序时,文件的格式是这样的。我知道我的代码段中包含了分段错误,但我不知道在哪里。我只能假设它与fgets()有关。但是,我查找的资源都没有任何内容可以让我认为我使用的不正确。它甚至可以在我使用fgetc,一次读取一次,为fgetc返回一个int时进行调整,这与fgets为变量分配一个字符串(在本例中为s)不同。

我不会把它带到堆栈溢出,除非我确定我找不到它;我一直在梳理代码一小时试图找到这个seg错误,这对我没有任何意义。我知道Seg Fault就在这里,因为在它之后,它应该打印出整个拼图矩阵,但它并没有那么远。

int main(int argc, char *argv[]) {

    FILE* puzzlefile;
    char s[10];
    int i=0, j=0, skip;
    //open the file passed in via command line
    puzzlefile = fopen(argv[1], "r");

    for (i=0; i<9; i++){
        //get first string of 10 characters
        fgets(s,10, puzzlefile);
        for (j=0; j<9; i++){
            //read the numbers from s into the puzzle 2D
            //array, which takes ints. Ignore the 10th
            //character, which will be \n
            puzzle[j][i] = (int)(s[j]-'0');
        }
    }
    ...
}

1 个答案:

答案 0 :(得分:4)

你的问题似乎是这样的:

  for (j=0; j<9; i++)
                 ^^^ 

这应该是j++,而不是i++

相关问题