.txt文件中的动态多维数组

时间:2013-08-30 23:23:57

标签: c arrays multidimensional-array

我是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);

我无法继续,因为我不明白我哪里出错了。 求你帮忙。

1 个答案:

答案 0 :(得分:1)

for (j = 0; j < p; j++){
            Matriz[i][j] = (double*) malloc (n * sizeof(double));

应该是:

 for (j = 0; j < m; j++){
            Matriz[i][j] = (double*) malloc (n * sizeof(double));

希望你能在使用之前初始化你的记忆。