通过传递数组长度在函数内声明数组

Declaring an Array Inside a Function by Passing Its Length

本文关键字:数组 函数 声明      更新时间:2023-10-16

我想要一个函数,它接受一个正整数,然后声明一个数组,初始化它并打印它。以下代码适用于 GCC 编译器,但不适用于 MSVC 编译器。我收到错误

错误(活动(E0028 表达式必须具有常量值。参数"Length"的值(在第 5 行声明(不能用作常量

  1. 使用 MSVC 编译器执行此操作的好方法是什么?
  2. 这种差异有什么好的理由吗?

我的代码:

#include <iostream>
using namespace std;
void Print(const int Length)
{
    int Array[Length];
    for (int i = 0; i <= Length - 1; i++)
    {
        Array[i] = i;
        cout << Array[i];
    }
}
int main()
{
    const int L = 5;
    Print(L);
    return 0;
}

正如评论中指出的那样,您绝对应该使用 std::vector<int> .

如果希望数组只存在于函数Print 中,则可以使用 new 在堆栈上声明一个动态数组。但是,请注意内存使用情况,因为可以用大数字调用Print,并且会出现堆栈溢出(再次使用向量来避免这种情况(。

#include <iostream>
using namespace std;
void Print(const int Length)
{
    int *Array = new int[Length];
    for (int i = 0; i < Length; i++)
    {
        Array[i] = i;
        cout << Array[i];
    }
    delete [] Array;
}
int main()
{
    const int L = 5;
    Print(L);
    return 0;
}

编辑:这是基于矢量的正确解决方案:

#include <iostream>
#include <vector>
using namespace std;
void Print(const int Length)
{
    vector<int> Array;
    Array.resize(Length);
    for (int i = 0; i < Length; i++)
    {
        Array[i] = i;
        cout << Array[i];
    }
}
int main()
{
    const int L = 5;
    Print(L);
    return 0;
}

如果你真的想要一个动态分配的、固定大小的数组,请使用 std::unique_ptr 而不是 std::vector。

#include <iostream>
#include <memory>
void Print(const int Length){
    std::unique_ptr<int[]> Array = std::make_unique<int[]>(Length);
    for (int i = 0; i < Length; ++i){
        Array[i] = i;
        std::cout << Array[i];
    }
    Array.reset();
}