由于您传递的是 adouble **array_ptr
它不会修改函数外部的指针。
在 C++ 中,您可以通过将其设为引用来修复它(并使用new
,因为它是 C++)
int Malloc2D(int n, int m, double**& array_ptr) {
array_ptr = new double*[n]);
if (array_ptr == NULL) {
std::cout << "ERROR! new failed on line " << __LINE__ << "..." << std::endl;
return -1;
}
for (int i = 0; i < n; i++) {
array_ptr[i] = new double[m];
if (array_ptr[i] == NULL) {
std::cout << "ERROR! new failed on line " << __LINE__ << "..." << std::endl;
return -1;
}
}
return 0;
}
或者,以 C 风格的方式,我们可以使用另一个指针间接寻址(&test
在调用代码中使用来传递 的地址double ** test
)。
int Malloc2D(int n, int m, double*** array_ptr) {
*array_ptr = (double**) malloc(n * sizeof(double*));
if (array_ptr == NULL) {
std::cout << "ERROR! malloc failed on line " << __LINE__ << "..." << std::endl;
return -1;
}
for (int i = 0; i < n; i++) {
(*array_ptr)[i] = (double*) malloc(m * sizeof(double));
if ((*array_ptr)[i] == NULL) {
std::cout << "ERROR! malloc failed on line " << __LINE__ << "..." << std::endl;
return -1;
}
}
return 0;
}
或者您可以简单地首先返回指向数组的指针 - 但这需要对调用代码进行一些小的更改:
double** Malloc2D(int n, int m) {
double** array_ptr;
array_ptr = (double**) malloc(n * sizeof(double*));
if (array_ptr == NULL) {
std::cout << "ERROR! malloc failed on line " << __LINE__ << "..." << std::endl;
return NULL;
}
for (int i = 0; i < n; i++) {
array_ptr[i] = (double*) malloc(m * sizeof(double));
if (array_ptr[i] == NULL) {
std::cout << "ERROR! malloc failed on line " << __LINE__ << "..." << std::endl;
return NULL;
}
}
return array_ptr;
}