c++ - 将二维数组传递给 C++ 中的函数

标签 c++ function multidimensional-array

我在将二维数组传递给 C++ 函数时遇到问题。该函数应该打印二维数组的值。但是出现错误。
在函数 void showAttributeUsage(int)
数组下标的 int(int) 类型无效。
我知道问题出在我将特定数组传递给函数的语法上,但我不知道如何解决这个特定问题。
代码:

#include <iostream>

using namespace std;
void showAttributeUsage(int);
int main()
{
    int qN, aN;
    cout << "Enter Number of Queries : ";
    cin >> qN;
    cout << "\nEnter Number of Attributes : ";
    cin >> aN;
    int attVal[qN][aN];
    cout << "\nEnter Attribute Usage Values" << endl;
    for(int n = 0; n < qN; n++) { //for looping in queries
        cout << "\n\n***************** COLUMN " << n + 1 << " *******************\n\n";
        for(int i = 0; i < aN; i++) {     //for looping in Attributes
LOOP1:
            cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
            cin >> attVal[n][i];
            cout << endl;
            if((attVal[n][i] > 1) || (attVal[n][i] < 0)) {
                cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
                goto LOOP1;                  //if wrong input value
            }

        }

    }
    showAttributeUsage(attVal[qN][aN]);
    cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";

    getch();
    return 0;

}
void showAttributeUsage(int att)
{
    int n = 0, i = 0;
    while(n != '\0') {
        while(i != '\0') {
            cout << att[n][i] << " ";
            i++;

        }
        cout << endl;
        n++;
    }
}

最佳答案

我真的建议使用 std::vector :live example

void showAttributeUsage(const std::vector<std::vector<int>>& att)
{
    for (std::size_t n = 0; n != att.size(); ++n) {
        for (std::size_t i = 0; i != att.size(); ++i) {
            cout << att[n][i] << " ";
        }
        cout << endl;
    }
}

然后这样调用它:

showAttributeUsage(attVal);

关于c++ - 将二维数组传递给 C++ 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23892221/

相关文章:

c++ - 堆内存结构

c++ - 代码中未初始化的指针

c++ - 代码未使用特定名称函数编译

c++ - 在 C++ 中使用变量的值来引用变量的名称

php - MySQL数据库搜索返回多维数组?

c++ - 如何初始化无符号整数 uint8_t

c# - Azure Functions RunOnStartUp 在配置中设置而不是在编译时设置?

PHP 函数 : more arguments than expected

python - 哪种形状应该具有 LSTM NN 的输入和输出数据?

string - VBA:字符串和数组 - 将一维数组拆分为二维数组