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?
1 Answer 1
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.
Comments
Explore related questions
See similar questions with these tags.
newin C++, we havestd::vectorandstd::unique_ptr. Don't use arrays of arrays as a 2D array, rather use a 1D array with the sizex * yand map the accesses.