首页 > 解决方案 > 通过传递其长度在函数内部声明一个数组

问题描述

我想要一个函数,它接受一个正整数,然后声明一个数组,初始化它并打印它。以下代码适用于 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;
}

标签: c++functionconstants

解决方案


如果您真的想要一个动态分配的、固定大小的数组,请使用 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();
}

推荐阅读