我想创建一个函数,它接受一个整数作为它的参数,并在C++中返回一个数组.这是我想到的伪代码:
function returnarray(integer i)
{
integer intarr[i];
for (integer j = 0; j < i; j++) { intarr[j] = j; }
return intarr;
}
Run Code Online (Sandbox Code Playgroud)
我尝试了将returnarray声明为函数*返回指针的常用方法,但是我不能将整数作为参数.我也不能将j分配给intarr [j].我真的想避免指向一个int,因此我可以使用参数.
有没有办法做到这一点,能够将j分配给intarr [j]而不为它指针?
编辑:
忘了写我想避免矢量.我只有在必须的时候使用它们!(我的理由是我的).
感谢:D
Pup*_*ppy 10
您无法返回堆栈分配的数组 - 它将超出范围并释放内存.此外,C++不允许堆栈分配的可变长度数组.你应该使用std :: vector.
std::vector<int> returnarray(int i) {
std::vector<int> ret(i);
for(int j = 0; j < i; j++) ret[j] = j;
return ret;
}
Run Code Online (Sandbox Code Playgroud)
你的代码甚至不是有效的c ++,所以我假设你是初学者
使用 std::vector
#include <vector>
std::vector<int> yourFunction( int n )
{
std::vector<int> result;
for( int i = 0; i < n; ++i )
{
result.push_back( i );
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
免责声明:编码器手中没有触及代码.
干杯&hth.,
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |