+ 6

How do you make a function return an array?

I made a code to test it, but it gives me errors and I don't understand them. I think I have to change something on the line with int test(){ #include <iostream> using namespace std; int test(){ int array[3] = {1, 2, 3}; return array; } int main() { cout << test() }

1st Dec 2018, 7:34 AM
Qun Franken
Qun Franken - avatar
10 Answers
+ 8
Sorry but you cannot return an array from a function. But doesn't matter ! C++ offers various solutions. Don't try strange workarounds.. Instead use available features : 1) create your own class with all you need. 2) use the standard template library , it is standard! std::vector or std::array That way is easy to return an object and it's correct std::vector<type> function ( parameters) { std::vector<tipe > output; // code return output; }
1st Dec 2018, 8:12 PM
AZTECCO
AZTECCO - avatar
+ 6
You don't need to because C++ does this for you https://code.sololearn.com/cmM0pQC9B1ZY/?ref=app
1st Dec 2018, 7:54 PM
Infinity
Infinity - avatar
+ 3
#include <iostream> using namespace std; int *test( int array[] ) { return array; } int main() { int arr[3]={2,2,3}; int *p = test(arr); cout<<p[0]<<p[1]<<p[2]; }
1st Dec 2018, 8:52 AM
James
James - avatar
+ 3
return
3rd Dec 2018, 12:50 AM
Mostafa V.N
Mostafa V.N - avatar
+ 3
We see how simple returning an integer is because we just return a copy of the variable in that memory location, also called as pass by value. But with array it's a different story, since array is a continous block of memory, we just pass the address that points to start of array (pointer variable). Now to access the array we just keep adding one to access next block of memory. *(arr + 0) or arr[0] => 1st address *(arr + 1) or arr[1] => 2nd address *(arr + 2) or arr[2] => 3rd address *(arr + 3) or arr[3] => 4th address .. ... and so on Btw can we sonehow pass array with pass by value in C++ like we can in JavaScript?
10th Dec 2018, 5:54 PM
Morpheus
Morpheus - avatar
+ 2
you can also use static array, as knowing that the lifetime of static variable is throughout the program: https://code.sololearn.com/c2LBfZ076X5M/#cpp
1st Dec 2018, 12:06 PM
MO ELomari
MO ELomari - avatar
+ 2
Array is equivalent of pointer, int[] is same as int* char[] is same as char* Object[] is same as Object* So if you need an array out of function then return type should be a pointer and assign to same type variable. Example: int[] myArray = {1, 2, 3, 4, 5}; int* function(int* array) { // some operation on array return array; } int[] intArray = function(myArray) ;
3rd Dec 2018, 1:36 PM
đŸ‡”đŸ‡° Danish Khan đŸ‡”đŸ‡°
đŸ‡”đŸ‡° Danish Khan đŸ‡”đŸ‡° - avatar
+ 1
In C++, array is always passed by pass by reference. So as such you do not need to return the array.
4th Dec 2018, 4:16 AM
nikhil rai
nikhil rai - avatar
0
Thx, I'll try it
1st Dec 2018, 8:34 AM
Qun Franken
Qun Franken - avatar