-
arrays and pointers
i have this code
Code:
#include <iostream>
using namespace std;
int solve_array(int * array[][], int array_x, int array_y)
{
int solutions = 1;
if((array_x == 1) && (array_y==1))
return 1;
int array_1[array_x-1][array_y];
int array_2[array_x][array_y-1];
solutions = solve_array(array_1[][],array_x-1,array_y) + solve_array(array_2[][],array_x,array_y-1);
return solutions;
}
int main()
{
// problem, find number of routes.
// solution iterate through each possibility
int array[21][21];
cout << "the number of possible paths is: " << solve_array(array[][],21,21);
return 0;
}
i need to know how to use an array as an argument and not need a specific size, as it is recursive
-
You could try flattening the 2d array.
int answer = solve_array (&array[0][0], nrows, ncols);
This should make the first argument a pointer to the first element. Then in solve_array, you have to do the math array[ x * nrows + y ] for any array[x][y].
-
that works, but i would still like to know how to pass a multidimensional array
-
Well a multidimensional array requires sizes for all the dimensions, except for the first, which you didn't seem to want, because of the way you phrased your request.
If you are familiar with regular array syntax:
int solve_array (int array[]);
All you have to do is add another subscript with the size of the dimension inside. You can do this for n dimensions.
int solve_array (int array[][21], int array_x, int array_y);
The first argument can be the array name.
-
-
In C++, a std::vector<std::vector<int *> > can be used to simulate a 2D array of pointers to int. std::vectors keep track of their size.
In C, there are alternatives, but they require a lot of bookkeeping, so it is easy to get things wrong.
-
you could do something like this:
Code:
template<int Columns, int Rows>
int solve_array(int (&array)[Columns][Rows], int array_x, int array_y);
this way, you can pass in a statically sized array implicitly, and even dynamic arrays by specifying the number of x and y elements as template parameters.