【问题标题】:dynamically memory allocation of a matrix in an array of structure结构数组中矩阵的动态内存分配
【发布时间】:2018-03-07 15:51:51
【问题描述】:

我想制作一个结构数组,为结构和两个矩阵动态分配内存

typedef struct {
    int **cont;
    double **doubmat;
} libra;

int main(int argc, char *argv[]) {

    libra *arra = calloc(Nfr,sizeof(libra));

    for (i = 0; i < Nfr; i++) {
        arra[i].doubmat = calloc(Nmol, sizeof (libra));
    }
    for (i = 0; i < Nfr; i++) {
        for (j = 0; j < Nmol; j++) arra[i].doubmat[j] = calloc(Nmol, sizeof (libra));
    }

    for (i = 0; i < Nfr; i++) {
        arra[i].cont = calloc(Nmol, sizeof (libra));
    }
    for (i = 0; i < Nfr; i++) {
        for (j = 0; j < Nmol; j++) arra[i].cont[j] = calloc(Nmol, sizeof (libra));
    }
    }

但我的内存有些问题,计算过程中的数字取决于数组中结构的数量。我认为我在分配方面犯了一些错误。

有人有什么建议吗? 提前感谢您的帮助。

【问题讨论】:

  • 向我们展示一个完整的程序。例如Nfr 是什么?并告诉我们您遇到的具体错误。
  • Nfr 在输入中给出,Nfr = atoi(argv[5]); 。我认为存在分配错误,因为 arra[i].doubmat[j][k] 的内容取决于 Nfr。程序编译没有任何问题,最后没有任何分段错误消息。如果 Nfr 为 1,则 arra[i].doubmat[j][k] 中的数字是正确的。

标签: c arrays dynamic structure allocation


【解决方案1】:

您指定了不正确的 sizeof(type) 来为矩阵分配内存。 你需要这样做:

typedef struct {
    int **cont;
    double **doubmat;
} libra;

int main(int argc, char *argv[]) {

    libra *arra = calloc(Nframe,sizeof(libra));

    for (i = 0; i < Nfr; i++) {
        arra[i].doubmat = calloc(Nmol, sizeof(*arra[i].doubmat));
        for (j = 0; j < Nmol; j++)
            arra[i].doubmat[j] = calloc(Nmol, sizeof(**arra[i].doubmat));
    }

    for (i = 0; i < Nfr; i++) {
        arra[i].cont = calloc(Nmol, sizeof(*arra[i].cont));
        for (j = 0; j < Nmol; j++)
            arra[i].cont[j] = calloc(Nmol, sizeof(**arra[i].cont));
    }
}

【讨论】:

    【解决方案2】:

    假设声明了 NFrame,我将展示一个由Nframe 结构组成的数组的分配,每个结构都包含一个NrowsxNcolsdoubmat

    typedef struct {
        int **cont;
        double **doubmat;
    } libra;
    
    int main(int argc, char *argv[]) {
    
        int i, j, Nrows = ..., Ncols = ...;
        libra *arra = calloc(Nframe, sizeof(libra));
    
        for (i = 0; i < Nframe; i++) {
            arra[i].doubmat = calloc(Nrows, sizeof(double*));
            if (arra[i].doubmat == NULL)
                return;
            for (j = 0; j < Nmol; j++){
                arra[i].doubmat[j] = calloc(Ncols, sizeof(double));
                if (arra[i].doubmat[j] == NULL)
                    return;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 2013-12-25
      • 2021-08-27
      • 2020-04-18
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多