My question is simple, if I have a matrix created on the stack rather than on the heap, such as int matrix[10][10]
, how can I pass it by reference? Or, pass it in a way that it doesn't pass the whole matrix as argument, but just its pointer or reference, or whatever. I use C++11.
void proc(/*WHAT GOES HERE?*/ matrix, int n){
matrix[n-1][n-1] = 7;
}
int main(){
int matrix[10][10];
proc(matrix, 10);
return 0;
}
You simply need:
// By reference:
void proc_ref(int (&matrix)[10][10]); // first dimension must have a size of 10
// By pointer:
void proc_ptr(int (*matrix)[10], int n); // n is the size of the first dimension
In the first case, matrix
will be a reference to an array of 10 array of 10 ints ("reference to int[10][10]
"), in the second case matrix
will be a pointer to an array of 10 int
("pointer to int[10]
").
In both cases you can use it like you want in proc
:
matrix[i][j] = 42;
The second version allows passing matrix of various size such as int[14][10]
or int[12][10]
(as long as the second dimension as a size of 10). It also allows passing dynamically allocated array of array of 10 int
:
int (*p)[10] = new int[42][10];
proc_ref (p); // Error
proc_ptr (p, 42); // Ok
int m[24][10];
proc_ref (p); // Error
proc_ptr (p, 24); // Ok
If you want to only allow square matrix declared with automatic storage duration, use the reference versions.
Note: You have to specify the second dimension of your matrix at compile time. If you want to be "generic" you could use a template:
template <size_t N>
void proc (int (&matrix)[N][N]);
Also, if you are using c++11, you should use std::array
which is much more convenient while still doing exactly what you want (no dynamic allocation):
template <typename T, size_t N>
using matrix_t = std::array<std::array<T, N>, N>;
template <typename T, size_t N>
void proc (matrix_t<T, N> &matrix) {
matrix[N - 1][N - 1] = 7;
}
int main () {
matrix_t<int, 10> matrix;
proc(matrix);
}
Array might decay to pointer. You can declare the parameter type as a pointer (to array) like:
void proc(int (*matrix)[10], int n){
matrix[n-1][n-1] = 7;
}
Note the dimension won't be reserved when array decaying to pointer, means you might pass int [11][10]
to proc()
in this case.
If you don't want this, you can declare the parameter type as reference like:
void proc(int (&matrix)[10][10], int n){
matrix[n-1][n-1] = 7;
}
Only int[10][10]
could be passed here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With