0

This is a part of my program to multiply 2 Matrices.

int m1, m2, n1, n2;
int first[m1][n1], second[m2][n2], result[m1][n2];
cout<<"Please enter no.of rows and columns of the 1st Matrix, respectively :";
cin>>m1>>n1;

And I am getting these Errors

error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2057: expected constant expression
error C2087: '<Unknown>' : missing subscript
error C2133: 'first' : unknown size

I am typing this code in Visual C++ 6.0 (Very old version), because this is currently what is taught to us at school. Please help me to get rid of these errors. Thanks in advance.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Mujtaba
  • 11
  • 4
  • I don't know if you are allowed to initialize array sizes with variables... are `m1` `m2` `n1` and `n2` defined before the initialization of the multidimensional arrays? Did you test the program by replacing the variables with actual numbers? – ahitt6345 Mar 27 '16 at 20:16
  • You are using the variables before they are initialized – lost_in_the_source Mar 27 '16 at 20:21
  • Use the heap. Do something like this: int **first = new int*[m]; for(int i = 0; i < m; i ++){ first[i] = new int[n]; } – user222031 Mar 27 '16 at 20:23

2 Answers2

0

You must assign some numbers to those variables(m1, m2, n1, n2) before using them to initialise some arrays. When you don't give them some values, initially, they are 0. Apparently, you can't create an array with a size of 0 and it's logical. The size of an array is constant and a 0 sized array is meaningless.

Maybe you need to try something like this:

int m1, m2, n1, n2;

cout << "Please enter no.of rows and columns of the 1st Matrix, respectively :";
cin >> m1 >> n1;

cout << "Please enter no.of rows and columns of the 2st Matrix, respectively :";
cin >> m2 >> n2;

int first[m1][n1], second[m2][n2], result[m1][n2];
Burak Tutanlar
  • 140
  • 2
  • 11
0

You have to use const values (the values are known during compilation time) when you want to initialize an array like this. For example:

const int r = 1, c = 2;
int m[r][c];

However, in your case you don't know the size during compilation. So you have to create a dynamic array. Here is an example snippet.

#include <iostream>

int main()
{
    int n_rows, n_cols;
    int **first;
    std::cout << "Please enter no.of rows and columns of the 1st Matrix, respectively :";
    std::cin >> n_rows >> n_cols;

    // allocate memory
    first = new int*[n_rows]();
    for (int i = 0; i < n_rows; ++i)
        first[i] = new int[n_cols]();

    // don't forget to free your memory!
    for (int i = 0; i < n_rows; ++i)
        delete[] first[i];
    delete[] first;

    return 0;
}
Lukas
  • 1,320
  • 12
  • 20