user12354664
user12354664

Reputation:

C++expression must have constant value

I have written this code in dev c++ and it works but when I try to run it in Visual Studio it gives an error like expression must have constant value.

#include <iostream>
using namespace std;

int main() {
    int r, c, j;
    int matrix[r][c];
    cout << "Enter the size of matrix: ";
    cin >> j;

    for (r = 0; r < j; r++) {
        for (c = 0; c < j; c++) {
            cout << "matrix" << "[" << r << "]" << "[" << c << "] = ";
            cin >> matrix[r][c];
        }
    }

    cout << "\n";
    for (int i = 0; i < j; i++) {
        for (int k = 0; k < j; k++) {
            cout << " "<<matrix[i][k] << " ";
        }
        cout << "\n";
    }




    return 0;

}

Upvotes: 2

Views: 338

Answers (3)

Grilled_Cheese
Grilled_Cheese

Reputation: 1

the size of a built-in array must be known at compile time, you can't set (or change) it at run time.

if you are learning alone from a tutorial and this tutorial is teaching you to use built-in arrays, I suggest you learn from a book instead like the ones posted above.

Simply put: an std::vector<int> is like an array of integers, and you can change its size at runtime. the dimensions of a built-in int matrix[5][5] can't be changed at runtime and must be decided while you are writing your program, which is not efficient.

Upvotes: 0

user12354664
user12354664

Reputation:

I have updated my code like this:

#include <iostream>
using namespace std;

int main() {
    int r, c, j,i,k;
    cout << "Enter the size of matrix: ";
    cin >> j;
    int matrix[j][j];

    for (r = 0; r < j; r++) {
        for (c = 0; c < j; c++) {
            cout << "matrix" << "[" << r << "]" << "[" << c << "] = ";
            cin >> matrix[r][c];
        }
    }
    cout << "\n";

    for ( i = 0; i < j; i++) {
        for ( k = 0; k < j; k++) {
            cout << " "<<matrix[i][k] << " ";
        }
        cout << "\n";
    }
}

Now, it works with Devc++. I am beginner in c++ and it is a little bit difficult for me to understand std::vector. So, that's why I did smth like this.

Upvotes: 0

Blaze
Blaze

Reputation: 16876

The reason why it's not working in Visual Studio is because that's a variable-length array, and those aren't actually part of C++. Some compilers tolerate it nevertheless, but VS won't.

The reason why you couldn't get the correct result regardless is because r and c aren't initialized here:

int r, c, j;
int matrix[r][c];

That's undefined behavior. My recommendation is using a nested std::vector (and making it after you read in the size):

#include <vector>
...
int r, c, j;
cout << "Enter the size of matrix: ";
cin >> j;
std::vector<std::vector<int>> matrix(j, std::vector<int>(j));

Upvotes: 6

Related Questions