我是 C 的初学者,我正在尝试执行动态分配到文件 input.txt 并从中读取的操作。问题是我找不到导致“分段错误”的错误。将分配矩阵并执行越来越多的操作以找到“+”或“-”符号。当你找到 '=' 符号时,我会将结果打印到文件 output.txt 中。
我的初始代码是这样分配数组的:
#include <stdio.h>
#include <stdlib.h>
double ***AlocarMatriz(int p, int m, int n)
{
int i, j;
double ***Matriz;
Matriz = (double***) malloc (p * sizeof(double**)); // alloc number of plans
for (i = 0; i < p; i++){
Matriz[i] = (double**) malloc (m * sizeof(double*));
if (Matriz[i]==NULL)
printf("plain"); // alloc rows
for (j = 0; j < p; j++){
Matriz[i][j] = (double*) malloc (n * sizeof(double));
if (Matriz[i][j]==NULL)
printf("plain"); // alloc cols
}
}
return Matriz;
}
void ImprimeMatriz(double ***Matriz, int p, int m, int n)
{ // print matrices
int i, j, k;
for(i = 0; i < p; i++){
for(j = 0; j < m; j++){
printf("\n");
for(k = 0; k < n; k++){
printf("%.2lf ", Matriz[i][j][k]);
}
}
}
}
int main(int argc, char *argv[])
{
double*** A;
int x, y, z;
scanf("%d", &x);
scanf("%d", &y);
scanf("%d", &z);
A = AlocarMatriz(x, y, z);
//double A[x][y][z];
ImprimeMatriz(A, x, y, z);
system("PAUSE");
return 0;
}
我试图创建一个代码来读取文件并获取如下所示的数组:
2 //instances - number of operations
2 2 2 //dimension of matrix - plan, row and column
0 1 // first matrix
1 0
0 1
1 0
+ //operation
0 1 //second matrix
1 0
0 1
1 0
= //flag for stop and print result in output.txt file
我打开txt文件的代码:
FILE *fent;
//int m, n, p, i, j, k;
if (argc != 3) {
fprintf(stderr, "Entry with correct params numbers!!!\n");
exit(1);
}
fent = fopen (argv[1], "r"); //try open file
if (fent == NULL) {
fprintf("Error to open %s for entry \n", argv[1]);
return -1;
}
fclose(fent);
return (EXIT_SUCCESS);
我无法继续,因为我不明白我哪里出错了。谢谢你的帮助。