return C++ arrays

I read that C++ arrays can't be returned by functions (as opposed to vectors)...anyone able to explain why?
It's mainly a syntax thing. There's simply no way to write code which accomplishes it. You can 'fake' it by encasing the array inside a struct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct somearray
{
  int foo[10];
};

somearray func()
{
  somearray bar;
  bar.foo[0] = 0;
  return bar;  // works as expected
}

int main()
{
  somearray test = func();
  return 0;
}


However this is generally a very bad idea because returning large objects is a huge waste (it generally involves a copy). You're better off passing the array by reference to the function, and changing it that way:

1
2
3
4
5
6
7
8
9
10
11
void func(int* foo)
{
  foo[0] = 0;
}

int main()
{
  int test[10];
  func(test);
  return 0;
}


That code does more or less the same thing, but doesn't require the array to be copied around (not to mention it's less code to type anyway).
Hy Joe101!
What Disch said is corect, but remember that there is no way of knowing the size of the array inside the function, except if it is a char array, because a char array always ends with a NULL, so you know where it stops.At least as far as i know.
But if you want to manipulate all the elements of the array and the array is not a char array, then you will also have to pass the "length" of the array to the function, or at least the number of elements after the function should stop.
Check out the code bellow, it tries to multiply by 3 all the elements of the array.
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<iostream>

using namespace std;

void triple_array(int *array,int &n) // the function that triples the value of n elements of the array
{
  int i;
  for(i=0; i<n; i++)
  {
    array[i] = array[i]*3; // triples the value of each element
  }
}

int main()
{
  int i=0;
  int n=0;
  int my_array[20];

  cout<<"Enter the number of elements of the array (max 20)"<<endl;
  cin>>n;

  if(n > 20)
  {
    cout<<"You entered a number larger than 20"<<endl;
    return 0;
  }

  for(i=0;i<n;i++)
  {
    cout<<"enter element ["<<i<<"]"<<endl;
    cin>>my_array[i];
  }

  triple_array(my_array,n); // it also receives n as a parameter to know where to stop

  for(i=0;i<n;i++)
  {
    cout<<"element ["<<i<<"] is "<<my_array[i]<<endl;
  }

  return 0;

}

Last edited on
Topic archived. No new replies allowed.