an array question

>hi i am a begginer in c++ programming;
>i know that arrays cannot return values from a function, but structures can.
>if i wanted to return an array, how could i reformat my data to accomplish >this?
>are there any drawbacks?
>thanx
You can pass the array as a parameter and modify it in the function.

Or else

struct Array {
int array[ 10 ];
};

In order to return arrays you should use vector<> and return that from a function. Vector is also compatible with POD arrays so you should have no trouble using them - prefer vectors before arrays, they are dynamic have a lot of other useful functionality

1
2
3
4
5
6
7
8
std::vector<int> myfunc( int a[], int size )
{
  std::vector<int> v(&a[0], &a[size]);

  <do your thing with v>

  return v;
}


BTW you can return arrays from a function, you just need to return the pointer to the array

1
2
3
4
5
6
7

int* myfunc(int a[], int size)
{
   <...>   
   return static_cast<int*>(a);
}


or

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int* myfunc()
{
   int *v = new int[size];

  <...>

   return v;   

   // although the above is not recommended for various reasons
   // size must be known by caller already, caller needs to take ownership
   // so its much better to use a vector 
}


hth
Topic archived. No new replies allowed.