I think the misunderstanding is that void eig(int n, double **A)
does not denote a "pointer to a 2D-array" but a pointer to a pointer to a double value.
Depending on what you do with A
in function eig
, this can be meaningful or not: If eig
is about allocating or reallocating a new array, then you'd use a double **A
in order to pass back the newly allocated memory to the caller. However, if you just want to access the values of the array, it's sufficient to pass just a pointer to the array (not a pointer to a pointer). See the following code explaining the difference. Hope it helps.
void eig1(int n, double **A) {
*A = new double [n*n]; // OK; pass back the array by writing its starting address into the pointer to which A points.
}
void eig2(int n, double *A) {
A = new double [n*n]; // does not make sense; changes local variable `A` only; will result in a memory leak
}
void eig_populate(int n, double *A) {
for (int i=0;i<n;i++) {
A[i]=i; // OK; does not allocate a new array but accesses an existing one
}
}
int main(){
double *HMAT = nullptr;
eig2(5,HMAT); // will not change HMAT
eig1(5,&HMAT); // will change HMAT
eig_populate(5, HMAT);
}