Returning an array from a function
Jul 19, 2010 at 6:13am UTC
Hi, What are the different ways of returning an array from a function? Which is the best? Thanks.
Jul 19, 2010 at 7:18am UTC
You can return a pointer pointing to a dynamically generated array or use some sort of container class
Jul 19, 2010 at 7:26am UTC
Ummm maybe you can return an address in a funtion to obtain an array
Here is an example..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
using namespace std;
double *array_return(int n){
double *new_array = new double [n];
for (int i=0;i<n;++i) new_array[i] = 0.0;
return new_array;
}
int main()
{
int n = 10;
double *ptr;
ptr = array_return(n);
for (int i=0;i<n;i++) cout << *(ptr+i) << endl;
return 0;
}
You can see above the function return an address and in the main function ptr is the first element of the array then you can access the other elements of array using fot loop
Jul 19, 2010 at 8:23am UTC
Thanks for the replies.
Topic archived. No new replies allowed.