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];
void function(int *board[boardSize]){}
function(board);
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);
Small code for creation and passing a dynamic double dimensional array to any function. `
void DDArray(int **a,int x,int y)
{
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
}
int main()
{
int r=3,c=5,i,j;
int** arr=new int*[r];
for( i=0;i<r;i++)
{
arr[i]=new int[c];
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<"Enter element at position"<<i+1<<j+1;
cin>>arr[i][j];
}
}
DDArray(arr,r,c);
}
`
You can pass a pointer to an pointer:
void someFunction(int** board)
{
}
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