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];
        }
4
  • 1
    thats not a 2d array..its a one dimensional array of int*s. Commented Feb 21, 2012 at 7:32
  • It would be after I loop through it an allocate every position Commented Feb 21, 2012 at 7: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 Commented Feb 21, 2012 at 7:37
  • possible duplicate of How do I use arrays in C++? Commented Feb 21, 2012 at 7:43

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You can pass a pointer to an pointer:

void someFunction(int** board)
{


}

Comments

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

}

`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.