Pass 2D array by refrence in cpp

c

#1

Here are two functions:
I am passing visited 2D array by reference from maxReign() to traverse(). But getting error: error: use of parameter outside function body before ‘]’ token
int traverse(int n, bool visited[][n], vector<vector> grid,int x, int y)

#include <vector>
using namespace std;


int traverse(int n, bool visited[][n], vector<vector<int>> grid,int x, int y){
    int storeA[] = {-1, -1, -1, 0, 0, 1, 1, 1};
    int storeB[] = {-1, 0, 1, -1, 1, -1, 0, 1};
    int count = 0;
    for(int k =0; k<8; k++){
        if(grid[x+storeA[k]][y+storeB[k]] == 1 || isValid(x+storeA[k], y+storeB[k], n)){
            visited[x+storeA[k]][y+storeB[k]] = true;
            count++;
        }
    }
    return count;
}

int maxRegion(vector<vector<int>> grid) {
    bool visited[grid.size()][grid[0].size()];
    for(int i =0; i<grid.size(); i++){
        for(int j =0; j<grid[0].size(); j++){
            visited[i][j] = false;
        }
    }
    int maximum = -1, m = -1;
    
    for(int i =0; i<grid.size(); i++){
        for(int j =0; j<grid[0].size(); j++){
            if(visited[i][j] == false){
                int m = traverse(grid[0].size(), visited, grid, i, j);
                maximum = max(maximum, m);
            }
        }
    }
    return maximum;
}

I am passing column size (n) before passing visited array in traverse array, but I am getting this error.


#2

Like it says, you use n outside the function body.
You’d save yourself some trouble by using vectors instead
You might generally want to prefer vector unless you have a good reason for why an array would be more suitable
You might want to pass those vectors by reference to avoid making copies.

Oh and note that reference is different from pointer in cpp. An array is a pointer, it’s the address of the first value in the array. (meaning you can write its type as *int, or for an array (another pointer) of those, **int … but I’d still much prefer to use vectors over dealing with memory directly)


#3

Thanks for the help buddy!