### Pass 2D array by reference?

How do you pass 2D arrays by reference??
Like any other array: type (&name)[size1][size2]

 ``1234567891011121314151617181920`` ``````#include template void increment_2D(T (&a)[N][M]) { for(std::size_t n = 0; n < N; ++n) for(std::size_t m = 0; m < M; ++m) ++a[n][m]; } int main() { int a[3][3] = {1,2,3,4,5,6,7,8,9}; increment_2D(a); for(auto& r: a) { for(int n: r) std::cout << n << ' '; std::cout << '\n'; } }``````

online demo: http://ideone.com/NbWYQO
Last edited on
You could achieve your objective by passing through as a pointer. Remember that a multi-dimensional array is just a contiguous area of memory, so just interate through it:

 ``123456789101112131415161718192021222324`` ``````#include using namespace std; void print(int* matrix[], const int& rows, const int& cols) { for (int n = 0; n < rows*cols; ++n) { cout << (*matrix)[n] << endl; } } int main() { const int ROWS(2), COLS(5); int m[ROWS][COLS] = {{1,2,3,4,5}, {10,20,30,40,50}}; int* pMatrix[ROWS]; *pMatrix = m[0]; print(pMatrix, ROWS, COLS); return 0; }``````
Last edited on
Topic archived. No new replies allowed.