1

我正在尝试将文件中的值读取到此矩阵**a,但我总是Segmentation fault因为我的scanf. 你能解释一下我的错误吗?谢谢

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

    int**a;

    FILE * fp;

    int i, j, temp;
    int n = 8;
    fp = fopen("matrix.txt", "r");

    a = malloc(sizeof(int)*n);

    for (i = 0; i < n; i++)
        a[i] = malloc(sizeof(int)*n);

    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            fscanf(fp, "%d", a[i][j]);


    return 0;

}
4

2 回答 2

5

You need an ampersand in fscanf:

fscanf(fp, "%d", &a[i][j]);
                 ^

A second problem that could catch you is that you're using the wrong sizeof in the first malloc. You want sizeof(int *) instead of sizeof(int). A simple rule to avoid such issues is to just use:

a = malloc(n * sizeof *a);
于 2013-01-08T19:06:32.967 回答
3

The first mistake is here: a = malloc(sizeof(int)*n);.

You have to use int* type instead: a = malloc(sizeof(int*)*n);

于 2013-01-08T19:06:01.870 回答