0

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.

2
  • If this isn't for practice I recommend you to use a vector of vectors. It's much easier to handle. Commented Nov 30, 2009 at 10:44
  • A vector of vectors has its own set of problems. You don't usually want a jagged array, and vector of vectors don't have as good locality as a single contiguous 2d array Commented Nov 30, 2009 at 10:55

4 Answers 4

8

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];
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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++

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.