在 C++ 中交叉动态分配的二维数组时的侵入性值/地址
Intrusive values/addresses when crossing an dynamic allocated 2d array in c++
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
为什么0
和1.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;
当然,有更安全的方法可以做到这一点。但这可能是一个好的开始。
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 在 C++ 中交叉动态分配的二维数组时的侵入性值/地址
- 是一个二维数组的名称,它在C++中的第一个元素的地址
- C++ 中动态二维数组中的地址
- 不带列号的二维数组提供地址
- 正在将指针地址从二维数组传输到结构
- 我如何通过使用二维数组的地址来赋值
- 二维数组中元素的地址
- 在给定一个元素的地址下搜索一个二维数组