Function returning multiple dynamic arrays

Hello everyone,

A function in my program should return two arrays and a number. The problem is that the two arrays are dynamic - I cannot pre-define their size. I've searched online and this example would work for fixed-length arrays:

void foo(int &fe, int &fi, int fo)
{
fe += fo;
fi += fe;
return;
}

...main()...
int A=0, B=1, C=2;
foo(A,B,C);
cout << A <<'\t'; //A=2
cout << B <<'\t'; //B=3
cout << C <<'\n'; //C=2


Which kind of makes sense to me: the "foo" function uses the address of whatever you pass on to it as the first and second arguments. It doesn't actually return anything but modifies the variables from within itself. I'd like to stick to this method because I can at least approximately understand what's going on. Could you please help me modify it (if possible) to a situatiohn when we'd like to pass a 1-D array and a 2-D grid created like this:

double *row ;
double **grid ;

cout << "Input the number of rows: " ;
cin >> ROWS ;
cout << "Input the number of columns: " ;
cin >> COLS ;

row = new double [COLS] ;
grid = new double *[ROWS] ;
for(i = 0 ; i < ROWS ; ++i) grid[i] = new double [COLS] ;


Thank you!
Any takes, anyone?
Something like this?
1
2
3
4
5
6
7
8
9
10
11
void foo(double*& row, double**& grid, size_t& ROWS, size_t& COLS)
{
	cout << "Input the number of rows: " ;
	cin >> ROWS ;
	cout << "Input the number of columns: " ;
	cin >> COLS ;

	row = new double [COLS] ;
	grid = new double *[ROWS] ;
	for(size_t i = 0 ; i < ROWS ; ++i) grid[i] = new double [COLS] ;
}
Last edited on
Ah yes, makes sense now! I was trying it the other way around: I was using "&*". I've made a very basic program for it:
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 <new>

using namespace std ;

void test(int*& data, int n) ;

int main()
{
	int n, i ;
	int * data ;
	
	cout << "How many numbers would you like? " ;
	cin >> n ;

	data = new int [n] ;
	test(data, n) ;
	for (i = 0; i < n; i++) cout << data[i] << "\n" ;
}

void test(int*& data, int n)
{
	int i ;
	for (i = 0; i <= (n - 1); i++)  data[i] = i * 2 ;

}
Thanks for the help. :)
Last edited on
Topic archived. No new replies allowed.