【发布时间】:2018-04-10 13:59:39
【问题描述】:
我想将一个二维数组从主函数发送到另一个函数,并且我想返回一个一维数组。我不知道如何从 C++ 函数返回数组。当我为标量值(不是向量或数组)执行此操作时,它可以正常工作。但是对于数组,我遇到了问题。这是我的代码:
#include <iostream>
using namespace std;
float display(float n[3][2]); // declare my function
int main() // main function
{
float num[3][2] = { // a dummy 2D array
{3.3, 4.3},
{9.3, 5.3},
{7.3, 1.3}
};
float a[3];
a = display(num); // send array to display function // line 13
for(int i = 0; i < 3; ++i)
{
cout << "reurned array is : " << a[i] << endl;
}
return 0;
}
float display(float n[3][2]) // define my function
{
float b[3];
cout << "Displaying Values: " << endl;
for(int i = 0; i < 3; ++i)
{
b[i] = n[i][0];
for(int j = 0; j < 2; ++j)
{
cout << n[i][j] << " ";
}
}
cout << endl;
for(int i = 0; i < 3; ++i)
{
cout << "actual array is : " << b[i] << endl;
}
return b; // line 39
}
这是我得到的错误:
/main.cpp||In function ‘int main()’
/main.cpp|13|error: incompatible types in assignment of ‘float’ to ‘float [3]
/main.cpp||In function ‘float display(float (*)[2])’
/main.cpp|39|error: cannot convert ‘float*’ to ‘float’ in return
【问题讨论】:
-
在标题中不要使用“in C++”,为什么不直接标记c++?
-
在 C++ 中,使用
std::arrays 中的std::array或std::vectors 中的std::vector可能会更好。但是,出于性能原因,通常最好将二维数组数据存储在一维数组/向量中,例如,请参阅stackoverflow.com/questions/19913596/c-2d-array-to-1d-array 了解详细信息。 -
@DanielLangr
std::array<std::array<int,X>,Y>无论如何都是平坦的(使用连续内存)。
标签: c++