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

标签 c arrays multidimensional-array

我是 C 的初学者,我正在尝试执行动态分配给文件 input.txt 和从文件 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);

我无法继续,因为我不明白我哪里出错了。 感谢您的帮助。

最佳答案

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

并希望您能在使用前初始化您的内存。

关于c - .txt 文件中的动态多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18542830/

上一篇:c - 文件处理

下一篇:c - 保持c程序运行

相关文章:

java - 寻找更新多维数组的有效方法

c# - 将 List<double[]> 转换为 double[,]

c - Keil 中的 sprintf 令人讨厌的警告

c - 错误 255 <0xFF> 和 -1073741819 <0xC0000005>

c - 为什么我的指针运算在这个数组中失败

c++ - 生成唯一变量并重用它们

java - 在java中创建一个存储字符串和整数的数组

java - 创建一个从两个不同的整数数组返回一组特定整数的方法?

Ruby新手: Writing a method to read mulitple arrays from a file?

arrays - 使用 Arrayformula 将每一行相乘