Search code examples
carraysdynamicstructureallocation

dynamically memory allocation of a matrix in an array of structure


I would like to make an array of structure with dynamic allocation of memory for the structure and the two matrix

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

but i have some trouble with memory, the numbers during the calculation depends on the number of structure in the array. I think that I'm making some mistake with the allocation.

Anyone have some tips ? Thanks in advance for your help.


Solution

  • You have specified incorrect sizeof(type) to allocate memory for matrices. You need to do something like that:

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