在c++中传递并返回2D阵列
passing and returning a 2D array in c++
我在传入、编辑和从函数返回2D数组时遇到问题。我正在尝试使用指针来执行此操作,但无法使参数类型兼容。
#include <iostream>
using namespace std;
double** get2DArray(double *info[3])
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 2; j++)
if(i == j)
info[i][j] = 0;
double** out = info;
return out;
}
int main()
{
double stuff[2][3] = {{1, 3, 5},{2, 4, 6}};
double(*temp)[3] = stuff;
double** info = get2DArray(temp);
for(int i = 0; i < 3; i++)
for(int j = 0; j < 2; j++)
cout << info[i][j] << endl;
return 0;
}
因为2D数组和指针数组是两个不同的野兽。2D阵列只是一个序列。对于T arr[X][Y];
(其中X和T是整数常数),T[i][j]
根据定义是*(&(arr[0][0]) + i*Y + j)
。
但是对于指针数组,arr[i]
就是指针,您可以编写arr[i] = new int[10];
,这将导致2D数组出错。
如果你想把array[2][3]
(6个元素)看作array[3][2]
(我无法想象它的真实用例,但这正是你的代码所建议的),你可以写:
#include <iostream>
using namespace std;
double (*get2DArray(double (*info)[2][3]))[2][3]
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 2; j++)
if(i == j)
(*info)[i][j] = 0;
double (* out)[2][3] = info;
return out;
}
int main()
{
double stuff[2][3] = {{1, 3, 5},{2, 4, 6}};
double (*temp)[2][3] = &stuff;
double (*info)[3][2] = reinterpret_cast<double (*)[3][2]>(get2DArray(temp));
for(int i = 0; i < 3; i++)
for(int j = 0; j < 2; j++)
cout << (*info)[i][j] << endl;
return 0;
}
由于数组既不可复制也不可赋值,因此不能通过函数返回调用返回数组。
但是,您可以通过引用将数组传递到函数中。因此,将get2DArray
函数更改为:
template<std::size_t N, std::size_t M>
void get2DArray(double (&info)[N][M]) {
// ...
}
您可以通过引用传递任意维度的2d数组,并根据需要更改其内容实况演示。
现在,如果您希望更改发生在原始阵列的副本上(例如,stuff
),您可以使用std::copy
将stuff
复制到temp
,然后将temp
传递到get2DArray
:
double stuff[2][3] = {{1, 3, 5},{2, 4, 6}};
double temp[2][3];
std::copy(&stuff[0][0], &stuff[0][0] + 6, &temp[0][0]);
get2DArray(temp);
现场演示
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- C++ & Python:传递并返回从 python 到 c++ 的 2D 双指针数组
- 返回 2D 数组(在 C# 和 C++ 中)
- 将 2D 数组作为函数参数,并返回 2D 数组作为函数的返回类型
- 函数可以返回 2D 数组吗?
- 在 C++ 中返回 2D arrray
- 从类返回 2D 数组指针
- 分割故障在C 中返回2D矢量时
- 使用类型转换在 C++ 中返回 2D 数组
- C++ - 通过函数返回 2D 数组
- 在C++中传递和返回 2D 数组
- C++函数不返回 2D 数组
- 我不能在不使用指针的情况下返回 2d 数组!我正在制作一个井字游戏类型游戏,这是我的向上移动功能
- 如何在C++中返回 2D 字符串数组/矢量
- 从C++返回2d数组
- 如何调用对象/构造函数来返回2D数组
- 返回 2D 数组的 C++ "no matching function error"
- 在c++中传递并返回2D阵列
- 需要帮助返回2D数组C++