代码之家  ›  专栏  ›  技术社区  ›  user3704223

如何将矩阵读入结构内的双**数组?[已关闭]

  •  -3
  • user3704223  · 技术社区  · 7 年前

    我有一个内部有双**mat数组的结构,它是一个指向双值指针的指针。假设矩阵名为m,我可以用m.mat[I][j]将值放入数组吗?

    struct Matrix {
      size_t row;
      size_t col;
      double** mat;
    };
    typedef struct Matrix TMatrix;
    
    int readMatrix(TMatrix m) {
        for(int i=0; i<m.row; i++)
        {
          for(int j=0; i<m.col; j++)
          {
            if(!scanf("%lg ", (m.mat[i][j])))
               return 0;
          }
        }
       return 1;
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   4386427    7 年前

    类似于:

    #include <stdio.h>
    #include <stdlib.h>
     
    struct Matrix {
      size_t row;
      size_t col;
      double **mat;
    };
    typedef struct Matrix TMatrix;
     
    void initMatrix(TMatrix *m, int row, int col) {
        m->row = row;
        m->col = col;
        int i;
        m->mat = malloc(m->row * sizeof(double*));  // allocate array of double pointers
        for (i=0; i<m->row; ++i)
        {
            m->mat[i] = malloc(m->col * sizeof(double));  // allocate array of doubles
        }
    }
     
    void freeMatrix(TMatrix m) {
        int i;
        for (i=0; i<m.row; ++i)
        {
            free(m.mat[i]);
        }
        free(m.mat);
    }
     
    int readMatrix(TMatrix m) {
        for(int i=0; i<m.row; i++)
        {
          for(int j=0; j<m.col; j++)
          {
            if(scanf(" %lg", &m.mat[i][j]) != 1) return 0;
          }
        }
        return 1;
    }
     
     
    void printMatrix(TMatrix m) {
        for(int i=0; i<m.row; i++)
        {
          for(int j=0; j<m.col; j++)
          {
            printf("%f ", m.mat[i][j]);
          }
          printf("\n");
        }
    }
     
     
     
    int main(void) {
        TMatrix a;
        initMatrix(&a, 2, 3);
        if (!readMatrix(a))
        {
            printf("input error\n");
            return -1;
        }
        printMatrix(a);
        freeMatrix(a);
     
        return 0;
    }
    

    标准DIN

    1 2 3 4 5 6
    

    stdout公司

    1.000000 2.000000 3.000000 
    4.000000 5.000000 6.000000