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?

asked Sep 18, 2014 at 13:18
3
  • possible duplicate of How do I declare a 2d array in C++ using new? Commented Sep 18, 2014 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 Commented Sep 18, 2014 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. Commented Sep 18, 2014 at 13:27

1 Answer 1

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.

answered Sep 18, 2014 at 13:27
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.