NUMI does not have rows and columns, it is a pointer-to-pointer-to-int, and happens to be pointing at an allocated memory that has room for dim
pointers-to-int, not dim * dim
ints. This would be equivalent to treating as having been declared int* NUMI[dim]
A call
int* NUMI;
NUMI= malloc( dim*dim*sizeof(int) );
will allocate a dim
by dim
matrix of integers.
However, please note that with multi-dimensional arrays, say int example[a][b]
, the size of the allocated area is equivalent to int* example_ = malloc(a*b*sizeof(int))
, and the compiler works out the conversion from multidimensional indices to a single-dimension index, i.e. example[c][d]
-> example_[c*a+d]
So when you do
int* NUMI;
NUMI= malloc( dim*dim*sizeof(int) );
//...
NUMI[i][i]= value2;
The compiler doesn’t have the information required to convert from the multiple dimension to the single-dimension equivalent.
PROB is similar, pointing to a memory area with room for dim
pointers-to-pointers-to-double, not dim * dim * dim
doubles.
To get a dim
cubed matrix, you’d need
double *PROB;
PROB = (double *)malloc( dim*dim*dim*sizeof(double) );
and run into the same problem with multi-dimensional indices.
If dim is a compile-time constant, you can declare the multidimensional arrays directly without malloc
double PROB[dim][dim][dim];
int NUMI[dim][dim];
The loop at the end of the main() should now work as expected.
If you must use malloc, either use malloc as described above:
NUMI= (int *) malloc( dim*dim*sizeof(int) );
PROB = (double *)malloc( dim*dim*dim*sizeof(double) );
and modify the loop body to
PROB[(ACT * dim * dim) + (ACTSTART * dim ) + i] = value;
NUMI[i + dim * i]= value2;
Alternatively, call malloc in multiple loops as described by Alexey and Paolo.
With my solution, there is one malloc()
call per variable, so each variable refer to a single contiguous memory area. With multiple malloc()
calls in loops, you have multiple allocated memory areas that is unlikely to be contiguous.
solved Allocate matrix of integer with c