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…
Arrays are not passed by value, so you can simply use
and, if you modify the values of
matinsidefuncyou 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: