当我尝试使用函数中通过引用传递的预分配矩阵读取值时出现分段错误

问题描述 投票:0回答:1

该函数有两个参数:char指针和整数三指针。整数三指针用于通过引用传递整数双指针(以便分配矩阵)。

我已经调试过,直到for循环的第二次迭代用于从文件中获取数字。

void leggimatrice(char *filename, int ***mat)
{
    int counter = 0, i, j, ap;
    FILE *fp;

    //count how many numbers there are in the file
    if ((fp = fopen(filename, "r")) != NULL) {
        while (fscanf(fp, "%d", &i) != EOF)
            counter++;
        fclose(fp);
    }
    //allocate the matrix; the value of counter is 9
    *mat = malloc(sizeof(int *) * sqrt(counter))
        for (i = 0; i < sqrt(counter); i++) {
        (*mat)[i] = (int *) malloc(sizeof(int) * sqrt(counter));
    }

    //reopen the file and save the values in the allocated matrix
    fp = fopen("matrice.txt", "r");
    for (i = 0; i < sqrt(counter); i++) {
        for (j = 0; j < sqrt(counter); j++)
            fscanf(fp, "%d", (mat[i])[j]);
    }
    fclose(fp);

    return;
}

结果是在第一个for循环的第二次迭代期间出现的分段错误(i = 1)

c dynamic segmentation-fault malloc pass-by-reference
1个回答
0
投票
if ((fp = fopen(filename, "r")) != NULL) {
...
fp = fopen("matrice.txt", "r");

这些不一定是打开相同的文件,所以(除非filename == "matrice.txt")你可能正在计算和阅读不同的文件。

SIGSEGV的真正原因在于:

fscanf(fp, "%d", (mat[i])[j]);

它应该是:

fscanf(fp, "%d", &(*mat)[i][j]);

或等效地:

fscanf(fp, "%d", (*mat)[i] + j);
© www.soinside.com 2019 - 2024. All rights reserved.