我有一个二维动态数组,想要将其传递给一个函数,应该如何操作?
int ** board;
board = new int*[boardsize];
//creates a multi dimensional dynamic array
for(int i = 0; i < boardsize; i++)
{
board[i] = new int[boardsize];
}
int **board;
board = new int*[boardsize];
for (int i = 0; i < boardsize; i++)
board[i] = new int[size];
fun1(int **);
请在下面的链接中检查2D数组的实现:
http://www.codeproject.com/Articles/21909/Introduction-to-dynamic-two-dimensional-arrays-in
void func(int **board) {
for (int i=0; i<boardsize; ++i) {
board[i] = new int [size];
}
}
func(board);
boardsize
或 size
不是全局变量,你可以通过参数传递它们。void func(int **board, int boardsize, int size) {
for (int i=0; i<boardsize; ++i) {
board[i] = new int [size];
}
}
func(board, boardsize, size);
void someFunction(int** board)
{
}
创建并传递动态双维数组到任何函数的小代码。
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);
}
`
int*
组成的一维数组。 - Naveen