5

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];
        }
Steffan Harris
  • 9,106
  • 30
  • 75
  • 101
  • 1
    thats not a 2d array..its a one dimensional array of `int*`s. – Naveen Feb 21 '12 at 07:32
  • It would be after I loop through it an allocate every position – Steffan Harris Feb 21 '12 at 07:35
  • @SteffanHarris: there is a big difference between a real 2D array, which in the end is one contiguous memory block and this dynamically allocated 'array of arrays'; where data is not guaranteed to be contiguous – KillianDS Feb 21 '12 at 07:37
  • possible duplicate of [How do I use arrays in C++?](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – Alok Save Feb 21 '12 at 07:43

4 Answers4

3
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

Ali
  • 1,256
  • 3
  • 15
  • 31
1

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);
Ade YU
  • 2,292
  • 3
  • 18
  • 28
0

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);

}

`

0

You can pass a pointer to an pointer:

void someFunction(int** board)
{


}
Alok Save
  • 202,538
  • 53
  • 430
  • 533