【问题标题】:Passing non-initialised variable to function with array as argument将未初始化的变量传递给以数组为参数的函数
【发布时间】:2014-12-01 12:02:52
【问题描述】:

对 C++ 相当陌生。 我的代码开头有这些声明:

#include <iostream>
#include <iomanip>
using namespace std;

int m, n;
void indtastVektor(double A[m]);
void indtastMatrix(double A[m][n]);

我的主要看起来像这样:

int main() {
    string svar;
    do {
        cout
                << "Ønskes indtastning af en vektor eller en matrix? Tast v for vektor og m for matrix: ";
        svar = cin;
        if (svar == "v" or svar == "V") {
            cout << "Indtast det ønskede antal rækker i vektoren som heltal: ";
            cin >> m;
            double vektor[m];
            indtastVektor(vektor);
            break;
        } else if (svar == "m" or svar == "M") {
            cout << "Indtast det ønskede antal rækker i matricen som heltal: ";
            cin >> m;
            cout << "Indtast det ønskede antal søjler i matricen som heltal: ";
            cin >> n;
            double matrix[m][n];
            indtastMatrix(matrix); // This line of code gives me an error
            break;
        } else {
            cout << "Intet gyldigt svar indtastet - forsøg igen. \n";
        }
    } while (true);
    return 0;
}

行:indtastMatrix(matrix);给我以下错误:

没有匹配的函数调用“indtastMatrix”

基本上,该函数采用用户指定的 m 和 n 并使用这些值创建一个二维数组。 Eclipse 给了我这个解释:

第一个参数没有从 'double [m][n]' 到 'double (*)[n]' 的已知转换 void indtastMatrix(double A[m][n]);

这到底是什么意思?我想我可能还需要在 main 函数之前初始化 m 和 n?

让我困惑的是这段代码没有返回任何错误:

cin >> m;
double vektor[m];
indtastVektor(vektor);

如果函数接受一维数组作为参数,我怎么能在运行时初始化变量并将其传递给函数,但如果它是二维的则不行?

谢谢!

【问题讨论】:

    标签: c++ arrays multidimensional-array initialization


    【解决方案1】:

    您正在使用可变长度数组 (VLA),它是一个非标准扩展。

    请改用std::vector。像

    void indtastVektor(std::vector<double>& v);
    void indtastMatrix(std::vector<std::vector<double>>& v);
    
    // ...
    
    std::vector<double> vektor(m);
    indtastVektor(vektor);
    
    //...
    
    std::vector<std::vector<double>> matrix(m, std::vector<double>(n));
    indtastMatrix(matrix); // This line of code gives me an error
    

    【讨论】:

      【解决方案2】:

      请记住,当您将数组传递给函数时,它们会衰减为指针。因此,数组数组衰减为指向数组的指针,类型为sometype (*)[size],其中size 是“内部”(第二维)数组的大小。

      但是,确切的大小必须在编译时在您定义或声明您的函数时知道。如果尺寸未知,您根本无法做到。不过有一个使用模板的解决方法:

      template<std::size_t SZ>
      void indtastMatrix(double (*A)[SZ]);
      

      另请注意,variable-length arrays 在某些编译器中是非标准扩展。请改用std::vector。

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        • 1970-01-01
        • 1970-01-01
        • 2012-11-27
        • 2020-09-26
        • 1970-01-01
        相关资源
        最近更新 更多