Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
possible duplicate of How do I declare a 2d array in C++ using new? –  Cyber 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. –  Conclusio Sep 18 '14 at 13:27

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.