salil03's blog

By salil03, history, 6 months ago, In English,

In c++, how do I pass multi-dimensional arrays in a function with variable lengths?

Thanks and regards

 
 
 
 
  • Vote: I like it
  • -7
  • Vote: I do not like it

»
6 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

You can use vectors, if needed. For example, if you have 2D array:

vector <vector<int> > v;

//push values here

f(v);

Then you can, call this in the function:

void f(vector<vector <int> > x)
{
    for(int i = 0; i < x.size()) //number of rows
        for(int j = 0; j < x[i].size()) //number of columns of i-th row
            //do something
}
  • »
    »
    6 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks, would it be possible using arrays?

    • »
      »
      »
      6 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Yes of course. If you have an 2D array of this:

      int** a = new int* [5];
      	
      for(int i = 0; i < 5; i++)
          a[i] = new int[10];
      		
      for(int i = 0; i < 5; i++)
          for(int j = 0; j < 10; j++)
              //fill the array
      			
      f(a, 5, 10); //pass array, and its sizes
      

      then all you need for function is:

      void f(int** arr, int rows, int cols)
      {
          for(int i = 0; i < rows; i++)
              for(int j = 0; j > cols; j++)
      	    //do something
      }