Arashdn
Arashdn

Reputation: 731

How to pass multidimensional dynamic arrays to function in c++

I have created a multidimensional dynamic array like this

int N;
cin >> N;
bool ** hap = new bool*[N];

for(int i = 0; i < N; i++)
hap[i] = new bool[N];

And It seems to work fine , But I need to pass this array to a function ...

How should I do this?

Thanks

Upvotes: 0

Views: 1000

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

In essence, the same as for returning a multi-dimensional array applies.

  1. Don’t use pointers and raw memory management here.
  2. Pass the object representing the array by (const) reference:
void f(matrix_2d const& mat) {
    // do something.
}

matrix_2d mat = { {1, 2}, {3, 4} };
f(mat);

For an appropriate definition of matrix_2d – for instance:

using matrix_2d = std::vector<std::vector<int>>;

(This code requires C++11 but the same applies in principle before.)

Upvotes: 1

RonaldBarzell
RonaldBarzell

Reputation: 3830

Pass it exactly as you declared it; as a bool **. Here's a sample definition:

void myFunc(bool** param)
{
    // Do stuff with param here, indexing it normally
}

Then you can just call the function like so:

myFunc(hap);

Upvotes: 2

Related Questions