Search code examples
c++arraysvisual-studiomultidimensional-arraydev-c++

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;

}

Solution

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