C++ 2D dynamic array crash
-
10-07-2019 - |
Question
Hi I'm having some problem with 2D dynamic array.
int main()
{
double **M;
int M_dimension;
int i;
M_dimension = 10;
M = new double *[M_dimension];
for (i=0;i<M_dimension;i++)
{
M[i] = new double[M_dimension];
}
M[0][0] = 1.0;
...
}
Program works but I'd like to initialize 2D array using such a function:
void initialize2D(double **M,int M_dimension)
{
int i;
M = new double *[M_dimension];
for (i=0;i<M_dimension;i++)
{
M[i] = new double[M_dimension];
}
}
Finally the program looks like this:
int main()
{
double **M;
int M_dimension;
int i;
M_dimension = 10;
initialize2D(M,M_dimension);
M[0][0] = 1.0; //crash
...
}
Unfortunately it crashes at M[0][0] = 1.0;
Thanks for any help or suggestions.
Solution
You are passing M
by value, instead of by reference. initialize2D
needs to change the value of the pointer-to-pointer M
such that it points to the memory allocated
Try changing your function signature to this instead:
void initialize2D(double **&M,int M_dimension)
Or
void initialize2D(double ***M,int M_dimension) {
...
*M = new double *[M_dimension];
...
}
OTHER TIPS
You need to pass a reference to double**
instead of double**
to function, otherwise the modification done to a pointer after assigning M the reslut of new
get lost on exit from a function.
what the problem might be is where you declaring an integer parameter such as int M_dimension void initialize2D(double **M,int M_dimension)
and then you initializing the dynamic array as: M[i] = new double[M_dimension];
where it comes to contradiction because you declared the variable M_dimension as an integer and then you using it as a double
try it this way: either change the data type of array or the M_dimension, so then both of them have the same data type.
hopefully this will help you out
Why don't you use std::vector
or Boost.MultiArray
It would be quite easy exercise to define 2-dimension array as generic vector of vectors in C++