0

I want to have a function which initializes dynamic 2d arrays in cpp like below

void initArrays(int n,double **a,double **b,double **c) {
a = new double*[n];
for (int i = 0; i < n; i++)
    a[i] = new double[n];
b = new double*[n];
for (int i = 0; i < n; i++)
    b[i] = new double[n];
c = new double*[n];
for (int i = 0; i < n; i++)
    c[i] = new double[n];
}

The function call completes but it does not initialize the pointers I give as function arguments. For example if I call this function in the main

double **x,**y,**z;
initArrays(3,x,y,z);

I cannot access

x[0][0]

what am I doing wrong here?

AlphaWolf
  • 319
  • 1
  • 3
  • 12
  • possible duplicate of [How do I declare a 2d array in C++ using new?](http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new) – Cory Kramer Sep 18 '14 at 13:19
  • This works if the init is done in the main which as explained in the question above. This failed when I moved the init to a function which is being called in the main – AlphaWolf Sep 18 '14 at 13:21
  • 1
    Don't use `new` in C++, we have `std::vector` and `std::unique_ptr`. Don't use arrays of arrays as a 2D array, rather use a 1D array with the size `x * y` and map the accesses. – Fytch Sep 18 '14 at 13:27

1 Answers1

4

The pointers stay uninitialized because you never assign them a value. The pointers in your init function are copies of the ones that you passed. You can pass the pointers by reference:

void initArrays(int n,double **&a,double **&b,double **&c)

That said, you'll probably be better off with std::vector.

eerorika
  • 232,697
  • 12
  • 197
  • 326