Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a 2d dynamic array to a function in C++

I have this 2d dynamic array and I want to pass it to a function, How would I go about doing that

int ** board;
        board = new int*[boardsize];

        //creates  a multi dimensional dynamic array
        for(int i = 0; i < boardsize; i++)
        {
            board[i] = new int[boardsize];
        }
like image 528
Steffan Harris Avatar asked Oct 08 '22 15:10

Steffan Harris


2 Answers

int **board; 
board = new int*[boardsize]; 

for (int i = 0; i < boardsize; i++)
    board[i] = new int[size];

You need to allocate the second depth of array.

To pass this 2D array to a function implement it like:

fun1(int **);

Check the 2D array implementation on below link:

http://www.codeproject.com/Articles/21909/Introduction-to-dynamic-two-dimensional-arrays-in

like image 195
Vishal Jaiswal Avatar answered Oct 12 '22 09:10

Vishal Jaiswal


You should define a function to take this kind of argument

void func(int **board) {
    for (int i=0; i<boardsize; ++i) {
        board[i] = new int [size]; 
    }
}

func(board);

If boardsize or size are not globlal, you can pass it through parameters.

void func(int **board, int boardsize, int size) {
    for (int i=0; i<boardsize; ++i) {
        board[i] = new int [size];
    }
}

func(board, boardsize, size);
like image 34
Ade YU Avatar answered Oct 12 '22 11:10

Ade YU