2

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!

  • 1
    the requirement of the function having only a single `int` argument sounds quite arbitrary. Is this really necessary? If yes, you can only make the matrix global, but it would be better to pass it as function parameter – 463035818_is_not_an_ai Dec 16 '16 at 14:44
  • 4
    Do you have to use an array? a `std::vector` would work nicely here. – NathanOliver Dec 16 '16 at 14:45
  • Well, according to what's written, it should look like int function (int i), so I suppose that it should only have one parameter-I'm also supposed to create the function switching the chosen columns and there, I have to pass it as a function parameter. However, how can I make the matrix global if its size is unknown before running the program? :) – BloodthirstyPlatypus Dec 16 '16 at 14:47
  • And I have to use array, otherwise I would surely use std::vector – BloodthirstyPlatypus Dec 16 '16 at 14:48
  • 1
    This will be messy in C++ if you can't use STL. It would then be better to use C, since it has VLAs. – Lundin Dec 16 '16 at 14:49
  • I'm really grateful for you help guys, but the rules were specified to me-I am supposed to use C++ and use arrays. I understand that there's no way to make a matrix "global"? :( – BloodthirstyPlatypus Dec 16 '16 at 14:50
  • Btw the question is unclear, as it is not obvious if `m` or `n` are rows or columns. Answers will depend on this. – Lundin Dec 16 '16 at 14:50
  • m-rows, n-columns. Sorry for not specifying that. – BloodthirstyPlatypus Dec 16 '16 at 14:50
  • If you have a specific array, attach your code (by editing the question) – Pavel Dec 16 '16 at 15:10
  • I did a matrix in my computer, you have to get the element [x][y] just with the column id... is it possible? No because it is in my computer. Some behaviour there. if you do not pass the matrix explicitely or implicitely no way to get the element. Explicitely just passing the pointer, or using the matrix as global variable. Implicitely wrapping the matrix in a class end declaring it static. Than each instance of this class is going to point to the matrix. Some other hacks here... But Is bad programming. Global variables, implicit declaration, are all member of the "bad programming family" – jurhas Dec 16 '16 at 15:31
  • It's an error in your code. `A[m][n] = rand() % 100;` writes values in the same place each time. It should be `A[a][b] = rand() % 100;` – Pavel Dec 16 '16 at 15:51
  • Yeah, I know. Now I corrected it and everything is working fine. – BloodthirstyPlatypus Dec 16 '16 at 17:13

4 Answers4

1

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.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
0

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

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

Pavel
  • 5,374
  • 4
  • 30
  • 55
  • 1
    Why would you use a pointer to pointer for? That alone suggests that you don't have a 2D array, but something else. – Lundin Dec 16 '16 at 15:28
0

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

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252