I am trying to modify the contents of a 2D array in C++ using a function. I haven't been able to find information on how to pass a 2D array to a function by reference and then manipulate individual cells.
The problem I am trying to solve has the following format. I have made a simple program for brevity.
#include<cstdlib>
#include<iostream>
using namespace std;
void func(int& mat) {
int k,l;
for(k=0;k<=2;k++) {
for(l=0;l<=2;l++) {
mat[k][l]=1; //This is incorrect because mat is just a reference, but
// this is the kind of operation I want.
}
}
return;
}
int main() {
int A[3][3];
int i, j;
char jnk;
for(i=0;i<=2;i++) {
for(j=0;j<=2;j++) {
A[i][j]=0;
}
}
func(A);
cout << A[0][0];
return 0;
}
So the value of A[0][0] should change from 0 to 1. What is the correct way to do this? Many thanks in advance...
can you check on this:
C++ allows you to encapsulate code structures like this into an object, for example an array has the
std::vector
andstd::array
object.I personally roll my own matrix containers. This way you don't have to worry about the details of how they are passed.
A basic example of a matrix implemenation could be:
Then you simply do the following:
Here's the conventional way. You can use either version of function "f":
Arrays are not passed by value, so you can simply use
and, if you modify the values of
mat
insidefunc
you are actually modifying it inmain
.You can use that approach if you know a priori the size of your matrix, otherwise consider working with pointers: