结构数组中矩阵的动态内存分配

dynamically memory allocation of a matrix in an array of structure

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

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

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

有人有什么建议吗? 在此先感谢您的帮助。

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

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

您指定了不正确的 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));
    }
}