Passing a 2d array into a method in c++

How does one do this? (or, better stated, what is the typical way of doing this in cp?)


Yes, I’ve looked on Stack Overflow, but it seems that the methods given either use hardcoded dimensions or require extra work to get it into the proper input. (like making the 2d array into a bunch of pointers to pointers.)

The only way that seems promising is using a template argument, but it doesn’t seem to work for variable sizes… (unless I’m doing something wrong.)

Code

(p is just a macro for getting an int from input.)

template <int rows, int cols>
void arr(int (&array)[rows][cols])
{
    cout<<array[0][0]<<endl;
}
int main() {
	fast;

	int r = p;
	int c = p;
	int test[r][c];
	arr(test);
	return 0;
}

Why not use vectors instead?

well for something like bottom-up dp or 2d grid representations I think a 2d array makes more sense (compared to a 2d vector) since you don’t need to resize anything

Why would a 2D vector be worse for the job? The performance difference is minimal, and they’re much safer than arrays.

So you’re saying there’s no reason to use arrays over vectors in c++?

Yes- the only advantage I could see is when you’re too lazy to write a 5D vector declaration.