该函数有两个参数: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)
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);