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

前端 未结 5 1506
长情又很酷
长情又很酷 2021-01-19 23:52

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

                


        
相关标签:
5条回答
  • 2021-01-20 00:22
      void function(int *board[boardSize]){}
    
    
      function(board);
    
    0 讨论(0)
  • 2021-01-20 00:23

    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);
    
    0 讨论(0)
  • 2021-01-20 00:28

    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 讨论(0)
  • 2021-01-20 00:42

    You can pass a pointer to an pointer:

    void someFunction(int** board)
    {
    
    
    }
    
    0 讨论(0)
  • 2021-01-20 00:44
    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

    0 讨论(0)
提交回复
热议问题