C ++函数返回数组 [英] C++ function to return array

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

问题描述

我需要我的函数返回一个数组,但它没有考虑数组作为参数,因为大多数的搜索示例显示。

I need my function to return an array, but it doesn't take an array as argument as most of search examples show.

在code是这样的:

double  myfunction ()
{
    double arr[10];
    //assign values to the array
    return arr;
}

main()
{
    double arr2[10];
    arr2[10] = myfunction;
    //print arr2
}

当我用指针来显示阵列,我得到了像CCCCCC...

When I used pointers to display the array, I got values like "CCCCCC"...

推荐答案

您不能这样做......数组的内存块,因此不能返回......你可以通过指针数组各地通过函数调用,但你不能安全地返回指向数组的内存块,除非这些阵列声明静态指针。否则,你会得到不确定的结果由数组占用堆栈上的内存将被回收当函数返回时,返回的指针堆栈内存位置将是无效的。使用返回的指针将最有可能损坏堆栈,或者你的程序崩溃。

You can't do that ... arrays are blocks of memory, and thus can't be "returned" ... You can pass pointers to arrays around through function calls, but you can't safely return pointers that are pointing to array memory blocks unless those arrays are declared static. Otherwise you will get undefined results as the memory on the stack occupied by the array will be reclaimed when the function returns, and the returned pointer to the stack memory location will be invalid. Using the returned pointer will most likely corrupt the stack, or crash your program.

在C你必须明确地使用一个指向堆分配的数组,为了避免这个问题,但与C ++使用将是最好的事情的std ::矢量的std ::阵列一个固定大小的数组。例如,的std ::矢量仍然使用堆内存来存储阵列(而不是堆栈),而是通过RAII堆内存安全地由对象的生命周期管理。因此,与C不同,你将不必从未能释放内存指向指针从被指向堆内存函数返回担心内存泄漏。

In C you would have to explicitly use a pointer to a heap-allocated array in order to avoid this issue, but with C++ the best thing to use would be std::vector or std::array for a fixed-size array. For instance, std::vector still uses heap memory to store the array (not the stack), but via RAII the heap memory is safely managed by the object's lifetime. Therefore unlike C you won't have to worry about memory leaks from failing to free the memory pointed to by pointers returned from functions that are pointing to heap memory.

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

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