BloodthirstyPlatypus
BloodthirstyPlatypus

Reputation: 79

How to use the same multidimensional array in many functions?

I'm a beginner at C++ and to be honest, I've got no idea how to solve one task. I have to create a matrix using a two dimensional array. It's size should be dependent on user's input (it should be like...int matrix[m][n], where m and n are the numbers entered by user). Then I'm supposed to fill it with random numbers from 0 to 100 and print it. Well, I can manage it. The problem starts when I have to create a function finding the highest number from this array's row. The only parameter of this function can be the number of row entered by user (eg. int function(int i)). The question is-how can I use the same array in multiple functions? Is there any way to do this, considering the fact that I'm a newbie? Or maybe the task is formed incorrectly? Sorry for the long post and thanks in advance PS Someone asked for code, so here it is:

#include <iostream>
#include <cstdlib>
using namespace std;
int function1(int i)
{
//this is one of the functions I'm supposed to create-I described it earlier
}
int main()
{
int m,n;
cout<<"Matrix's size will be m rows and n columns. Please write m and n"<<endl;
cin>>m>>n;
int A[m][n];
int a,b;
for (a=0;a<m;a++)
{
for (b=0;b<n;b++)
{
A[a][b]=rand()%(100+1);
    cout<<A[a][b]<<" ";
}
cout<<"\n";
}
}

EDIT: I'd like to thank you all for help guys. I asked my teacher about that and he finally responded. If you're curious, he told us (I hadn't heard it) to define an array like int[100][100] or higher and not allow user to input any higher numbers ;) That's not an optimal solution but surely a practical one. Thank you again!

Upvotes: 2

Views: 284

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 149135

The following is not standard C++ because it will only work if the compiler supports Variable Length Arrays. VLA were introduced in C99 and made optional in C11 but were never introduced in C++ standard - but some compilers support it even in C++ mode.

The hack will be to store the matrix address as a global void * and cast it to the proper pointer to VLA inside the function. This hack is required because at the moment of the global declaration you cannot know the number of columns of the matrix.

#include <iostream>
#include <cstdlib>

void *Matrix;
int Columns;

using namespace std;
int function1(int i)
{
    typedef int MAT[Columns];   // BEWARE!!! VLA is not standard C++
    MAT *mat = static_cast<MAT *>(Matrix);
    int mx = mat[i][0];
    for(int j=0; j<Columns; j++) {
        cout << " " << mat[i][j];
        if (mat[i][j] > mx) mx = mat[i][j];
    }
    std::cout << endl;
    return mx;
}
int main()
{
int m,n;
cout<<"Matrix's size will be m rows and n columns. Please write m and n"<<endl;
cin>>m>>n;
int A[m][n];         // BEWARE!!! VLA is not standard C++
int a,b;
for (a=0;a<m;a++)
{
for (b=0;b<n;b++)
{
A[a][b]=rand()%(100+1);  // Note that I now use a and b here !
    cout<<A[a][b]<<" ";
}
cout<<"\n";
}
Matrix = static_cast<void *>(A);
Columns = n;

cout << "Enter row number to process: ";
cin >> a;
b = function1(a);
cout << "Max of row " << a << " is " << b << endl;
return 0;
}

Not really C++-ish, but at least it compiles and give expected results with clang version 3.4.1

Upvotes: 0

Pavel
Pavel

Reputation: 5876

If you declare a matrix like int int A[m][n]; where m and n aren't const, you can't pass it to a function. There are two ways to fix it:

1) Declare matrix with const size like int A[10][10];. In this case function which finds max will look like this:

int max_in_row(int matr[10][10], int row) {
    int max = 0;
    for (int col = 0; col < 10; ++col)
        if (matr[row][col] > max)
            max = matr[row][col];
    return max;
}

and you can find max simple as int max = max_in_row(A, <row you want>);

2) (If you don't know size) Declare matrix as array of arrays:

int **A = new int*[n];
for (int i = 0; i < n; ++i)
    A[i] = new int[m];
// fill A like you did

Then the function will look like

int max_in_row(int **matr, int row, int m) {
    int max = 0;
    for (int col = 0; col < m; ++col)
        if (matr[row][col] > max)
            max = matr[row][col];
    return max;
}

and you can find max by int max = max_in_row(A, <row you want>, m);

Upvotes: 0

Godineau F&#233;licie
Godineau F&#233;licie

Reputation: 438

You can wrap your function into a class. In that class, you can have your array as member variable.

    class A { 
      int **matrix;

      public:
       A(int rows, int columns) {
        matrix = new int*[rows];
        for(int i = 0; i < rows; ++i)
          matrix[i] = new int[columns];
       }

   int function(int i); //you can use your matrix in this function
}

If you can't use classes, you can use global variables.

In a file.cpp

    int **matrix;

    int function(int i) {
       //Do Something
    }

//With rows the number of rows and columns the number of columns
//You can take these as parameters
    int main() {
       matrix = new int*[rows];
        for(int i = 0; i < rows; ++i)
          matrix[i] = new int[columns];
       function(42);
    }

Upvotes: 0

Lundin
Lundin

Reputation: 214740

The correct way to do this in C++ is to use a std::vector or std::array.

If you cannot do this because of artificial requirements, then there is simply no way you can declare a 2D array in C++ based on user input.

cin >> m >> n;
...
int array [m][n];  // not possible
int** wannabe;     // not an array
int array [m * n]; // not possible

What you can do is a "mangled" 2D array:

int* mangled = new int[m * n];

Example of use:

class int_matrix
{
  private:
    int*   mangled;
    size_t rows;
    size_t cols;

  public:
    int_matrix(size_t row, size_t col)
      :rows(row),
       cols(col)
    {
      mangled = new int[row * col];
    }

    int highest_in_row (size_t row)
    {
      ...
    }
};

Please note that this code requires that you follow the rule of three.


In C you would just have elegantly solved this by writing int array[m][n], but you are using C++ so you can't do that.

Upvotes: 1

Related Questions