Search code examples
cmultidimensional-arraymallocdynamic-arrays

allocate dynamic multiple array


Let's say we have the following design:

typedef struct {
  double **pdouble;
  int *pint
}foo;

now I want to allocate:

foo *pfoo;

the thing is that the total number of pdouble is known, lets say its n; if we say **pdouble is like pdouble [a][b], a is also known. means a*b =n. but b is dynamic. mean pdouble[1] might contain b column and pdouble[2] might have b' number of column, also b and b',b" ... will generate in the program gradually. its worth noting that b+b'+b"+ ... = n. is it possible to allocate foo using just knowing n and a?

I'm going to edit it a little so my question will become more understandable.

allocation_func(in size, int block_size)
foo *pfoo;

pfoo = (foo*) malloc(sizeof(foo))

/*some code here to do block_size number of *double which I don't know*/


foo->pdouble = (double**) malloc ( size * sizeof(double))

}

I ignored errors and other required thing which everybody knows.
Thats all;


Solution

  • First allocate struct memory

     foo *pfoo = malloc(sizeof *pfoo); 
    

    then allocate memory for struct member double **pdouble;

    //for example purpose i take 50x50 array
    
    pfoo->pdouble = malloc(50* sizeof(double *));
    
    for(int i=0;i<50;i++)
        pfoo->pdouble [i] = malloc(50* sizeof(double ));
    

    And finally allocate memory for struct member int *pint

     pfoo->pint=malloc(100*sizeof(int)); //100 is just for example