如何在C ++函数中返回数组? [英] How can I return an array in C++ functions?

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

问题描述

我是一个C ++ noob,我想知道如何从一个C ++函数返回一个数组。

我试过下面的代码,但似乎不工作。

I am a C++ noob and I wanna know how can i return an array from a C++ function.
I tried the following code but doesn't seem to work.

char some_function(){
    char my_string[] = "The quick brown fox jumps over the lazy dog";
    return my_string;
}


推荐答案

t工作是函数结束的分钟,所创建的字符串的生命周期。相反,如果你打算在C ++中使用 std :: string 并返回。

The reason that code isn't working is that the minute the function ends, so does the lifetime of the string you have created. Instead, if you're going to be working in C++ use std::string and return that.

std::string myFunc(){
    return string("hey a new string");
}

对于其他数组使用 std :: vector std :: deque 或其他STL类之一。我还要指向你看看STL(标准模板库):

For other arrays use std::vector, std::deque or one of the other STL classes. I'd also point you to look at the STL (standard template library):

vector<float> myFunc(){
    vector<float> blah;
    blah.push_back(4.5);
    blah.push_back(5.7);
    return blah;
 }

返回数组时:

指针等的大问题是对象生命周期的考虑。如下面的代码:

The big problem with pointers and such is object lifetime considerations. Such as the following code:

int* myFunc(){
    int myInt = 4;
    return &myInt;
}

这里发生的是,当函数退出 myInt 不再存在,留下指针返回指向一些内存地址,可能或不可能保持值4.如果你想使用指针返回一个数组(我真的建议你不要' t并使用 std :: vector ),它将看起来像:

what happens here is that when the function exits myInt no longer exists leaving the pointer that was returned to be pointing at some memory address which may or may not hold the value of 4. If you want to return an array using pointers (I really suggest you don't and use std::vector) it'll have to look something like:

int* myFunc(){
    return new int[4];
}

使用新运算符。

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

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