Allocate matrix of integer with c -


i have integer 2d matrix numi , 3d double matrix called prob.

here 2 allocation:

   int main ( int argc, char* argv[]){         double  ***prob;         int  **numi;             numi = (int **)malloc((dim)*sizeof(int *));         prob = (double ***)malloc((dim)*sizeof(double**));         ...             for( = 0; < n ; i++){             prob[act][actstart][i] = value;             numi[i][i]= value2;         }   } 
  • how many rows , cols has numi? dim x dim matrix???

  • prob 3d matrix...here allocation dim x dim x dim?

numi not have rows , columns, pointer-to-pointer-to-int, , happens pointing @ allocated memory has room dim pointers-to-int, not dim * dim ints. equivalent treating having been declared int* numi[dim]

a call

int* numi; numi= malloc( dim*dim*sizeof(int) ); 

will allocate dim dim matrix of integers.

however, please note multi-dimensional arrays, int example[a][b], size of allocated area equivalent int* example_ = malloc(a*b*sizeof(int)), , compiler works out conversion multidimensional indices single-dimension index, i.e. example[c][d] -> example_[c*a+d]

so when

int* numi; numi= malloc( dim*dim*sizeof(int) ); //... numi[i][i]= value2; 

the compiler doesn't have information required convert multiple dimension single-dimension equivalent.

prob similar, pointing memory area room dim pointers-to-pointers-to-double, not dim * dim * dim doubles. dim cubed matrix, you'd need

double  *prob; prob = (double *)malloc( dim*dim*dim*sizeof(double) ); 

and run same problem multi-dimensional indices.

if dim compile-time constant, can declare multidimensional arrays directly without malloc

double prob[dim][dim][dim]; int    numi[dim][dim]; 

the loop @ end of main() should work expected.

if must use malloc, either use malloc described above:

numi= (int *)    malloc( dim*dim*sizeof(int) ); prob = (double *)malloc( dim*dim*dim*sizeof(double) ); 

and modify loop body

prob[(act * dim * dim) + (actstart * dim ) + i] = value; numi[i + dim * i]= value2; 

alternatively, call malloc in multiple loops described alexey , paolo. solution, there 1 malloc() call per variable, each variable refer single contiguous memory area. multiple malloc() calls in loops, have multiple allocated memory areas unlikely contiguous.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -