从没有参数的函数返回整数数组 [英] Returning integer array from function with no arguments

查看:21
本文介绍了从没有参数的函数返回整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
通过 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.

这篇关于从没有参数的函数返回整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆