Returning integer array from function with no arguments(从没有参数的函数返回整数数组)
问题描述
可能重复:
通过 C 和 C++ 中的函数返回本地数据指针
我需要创建一个返回数组的不带参数的函数
I need to create a function with no arguments that returns an array
我收到错误:警告:函数返回局部变量的地址"
I get the error: "warning: function returns address of local variable"
为了便于阅读,我的代码已经过简化
my code has been simplified for ease of reading
int * getNums()
{
int nums[8];
nums = {1,2,3,4,5,6,7,8};
return nums;
}
我被引导明白,当函数结束时指针丢失了,但数组还会被发送吗?如果不是,那么在函数调用中返回这个不带参数的整数数组的好方法是什么?
I am led understand that when the function ends the pointer is lost, but will the array still be sent? If not, what is a good way to return this integer array with no arguments in the function call?
提前感谢帮助!
干杯
推荐答案
不,数组不会被发送".您需要执行以下操作之一:
No, the array will not be "sent". You need to do one of these:
- 使用 new 动态创建数组
- 静态创建数组
- 将数组作为指针传递给函数
- 使用 std::vector
在大多数情况下,最后一个是首选解决方案.
In most cases, the last is the preferred solution.
这篇关于从没有参数的函数返回整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从没有参数的函数返回整数数组


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16