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.
这篇关于从没有参数的函数返回整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从没有参数的函数返回整数数组
基础教程推荐
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
