Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return an array in C++ functions?

Tags:

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;
}
like image 494
SteepCurver Avatar asked Feb 26 '23 18:02

SteepCurver


2 Answers

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");
}

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;
 }

On returning arrays:

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

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

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];
}

which uses the new operator.

like image 68
wheaties Avatar answered Feb 28 '23 08:02

wheaties


In C++ it is better to use std::string over an array of char in almost every case.

More generally, consider the STL container classes rather than C-style arrays.

Here are a couple of examples...

#include <string>
#include <vector>

std::string some_function()
{
    return "The quick brown fox jumps over the lazy dog";
}

std::vector<std::string> some_other_function()
{
    std::vector<std::string> stuff;
    stuff.push_back("Spam");
    stuff.push_back("Spam");
    stuff.push_back("Spam");
    stuff.push_back("Spam");
    stuff.push_back("Spam");
    stuff.push_back("Spam");
    stuff.push_back("Spam");
    return stuff;
}
like image 45
Johnsyweb Avatar answered Feb 28 '23 07:02

Johnsyweb