Mar 15, 2013 at 4:19pm Mar 15, 2013 at 4:19pm UTC
How do you pass 2D arrays by reference??
Mar 15, 2013 at 4:43pm Mar 15, 2013 at 4:43pm UTC
Like any other array: type (&name)[size1][size2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
template <typename T, std::size_t N, std::size_t M>
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 Mar 15, 2013 at 4:43pm Mar 15, 2013 at 4:43pm UTC
Mar 15, 2013 at 4:55pm Mar 15, 2013 at 4:55pm UTC
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
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 Mar 15, 2013 at 5:07pm Mar 15, 2013 at 5:07pm UTC