How to return an array from a function?

How to return an array from a function in c++? I know there is a way for it by using pointers but can someone explain how? Also is there an easier way of doing it?

C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example:

int * myFunction() {
.
.
.
}
Second point to remember is that C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

In C++ we can easily return a VECTOR from a Function .

// Function

vector < int > solve ()

{

int n, i, value ;

cin>> n;

vector < int > temp;

temp.clear();

for( i=0; i < n; i++)

{

cin >> value;

temp.push_back(value);

}

return temp;

}

// Calling part :

vector < int> ans;

ans.clear() ;

ans = solve();

for( int i=0; i< ans.size(); i++)

cout << ans* << " " ;

//^ you can do whatever Operation you like !

//Hope this Helped. :smiley:

The below way works in both C and C++.

Just declare the array inside a struct. You can return the struct variable from any function.

3 Likes

I think it doesn’t allow return to array. Maybe my knowledge on that still dull. May someone enlighten me please, will greatly appreciate it

Return array from functions in C++ C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array’s name without an index.

Can you provide the code for how to do it

1 Like

@mathecodician from where are you learning the Data Structures & Algorithms? and how is your preparation for INOI going?

1 Like

http://ideone.com/ObRMZD go through this, an example, @mathecodician

@coder_voder My preparation is going good for INOI. I just completed all the past year ZCO problems. I am learning mainly by random online resources. But mostly from websited like khan academy, commonlounge, geekforgeeks, topcoder tutorials, iarcs study material, and mostly from youtube. But mainly I learning by doing practice problems.

1 Like