在 C++ 中交叉动态分配的二维数组时的侵入性值/地址

Intrusive values/addresses when crossing an dynamic allocated 2d array in c++

本文关键字:地址 二维数组 C++ 动态分配      更新时间:2023-10-16

2D 数组初始化:

....
int main (...) {
....
double **hes = allocArray (2, 2);
// function (....) returning double
hes[0][0] = function (3, &_X, &_Y, _usrvar_a, _usrvar_b);
hes[0][1] = function (4, &_X, &_Y, _usrvar_a, _usrvar_b);
hes[1][0] = function (4, &_X, &_Y, _usrvar_a, _usrvar_b);
hes[1][1] = function (5, &_X, &_Y, _usrvar_a, _usrvar_b);
....
return 0;
}
double **allocArray (int row, int col) {
double **ptr = new double*[row];
for (int i = 0; i < row; i++)
{
ptr[i] = new double[col];
}
return ptr;
}

二维双精度类型数组的值为:

12 2 2 14

我知道这一点,因为我已经用迭代器(i,j(交叉了它

void otherFunc (double **h, ....) {
....
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
std::cout << " " << h[i][j];
....
}

输出为

12 2 2 14

(我不需要在输出中分隔 2D 数组的行,不要写那个(

我想用指针交叉它:

void otherFunc (double **h, ....) {
.... 
for (double *ptr = h[0]; ptr <= &h[1][1]; ptr++)
std::cout << " " << *ptr;
....
}

输出为:

12 2 0 1.63042e-322 2 14

为什么01.63042e-322会出现在这里?

运行中的h[0]h[1]不是一前一后:h[1]在您的特定运行中恰好是h[0]之后的四个数字。

这种行为可能是随机的,这意味着(据我们从您的问题中知道(您可能没有明确指定h[0]h[1]的相对位置。如果是这种情况,下次运行代码时h[1]甚至可能小于h[0]这会导致未定义的行为。

您可能想要的是这样的东西:分配四个双精度并将第一个的地址分配给指针double* hh = malloc(4 * sizeof(double));然后对于变量h,这是一个指向指针的指针double* h[2];,您希望分配指针,如下所示:

h[0] = hh; 
h[1] = hh+2; 

当然,有更安全的方法可以做到这一点。但这可能是一个好的开始。