Returning arrays from a function

Extremely basic but something I obviously looked over and now I need it :) !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
   //create 2 arrays here to hold the int array and char array
   arrayFunction();
   return0;
}

int aarrayFunction();
{
   //does alot of maths here
   int numbers[3] = {1,2,3};
   char letter[3] = {t,y,u};
   //return both arrays
}
Last edited on
You can't return arrays because arrays have special rules in C++ that make them annoying to deal with.

You have two options:
- Pass both arrays to arrayFunction and have it fill them with values
- Use std::vector, which you can return from functions.

I recommend using std::vector. Arrays are a pain to deal with and don't work the way you think they do even when you think you know.
Last edited on
If the arrays are as in your code (size known at compile-time), you can just wrap them (and the compiler should be able to optimize away the copies):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <array>
#include <utility>

std::pair< std::array<int,3>, std::array<char,4> > array_function()
{
   //does alot of maths here
   std::array<int,3> numbers = { 1, 2, 3 } ;
   std::array<char,4> letters = { 't', 'y', 'u', 'w' } ;

   //return both arrays
   return { numbers, letters } ;
}

int main()
{
    auto p = array_function() ;

    auto int_array = p.first ;
    for( int i : int_array ) std::cout << i << ' ' ;
    std::cout << '\n' ;

    auto char_array = p.second ;
    for( char c : char_array ) std::cout << c ;
    std::cout << '\n' ;
}

http://ideone.com/Qwfqsz
Topic archived. No new replies allowed.