簡體   English   中英

C++ 表達式必須具有常量值

[英]C++expression must have constant value

我已經在 dev c++ 中編寫了這段代碼,它可以工作,但是當我嘗試在 Visual Studio 中運行它時,它會給出一個錯誤,比如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;

}

它在 Visual Studio 中不起作用的原因是因為這是一個可變長度數組,而這些實際上並不是 C++ 的一部分。 一些編譯器仍然可以容忍它,但 VS 不會。

無論如何您都無法獲得正確結果的原因是因為rc未在此處初始化:

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

那是未定義的行為。 我的建議是使用嵌套的std::vector (並您閱讀尺寸后制作):

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

內置數組的大小必須在編譯時知道,您不能在運行時設置(或更改)它。

如果您是從教程中單獨學習並且本教程正在教您使用內置的 arrays,我建議您從一本書中學習,而不是像上面發布的那樣。

簡單地說:一個std::vector<int>就像一個整數數組,你可以在運行時改變它的大小。 內置int matrix[5][5]的維度不能在運行時更改,必須在編寫程序時確定,這樣效率不高。

我已經像這樣更新了我的代碼:

#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";
    }
}

現在,它可以與 Devc++ 一起使用。 我是 c++ 的初學者,理解 std::vector 對我來說有點困難。 所以,這就是我這樣做的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM