简体   繁体   English

通过传递函数长度来声明函数内部的数组

[英]Declaring an Array Inside a Function by Passing Its Length

I want to have a function which takes a positive integer, then declares an array, initializes it and print it. 我想要一个带正整数的函数,然后声明一个数组,初始化它并打印它。 The following code works with a GCC compiler but it does not work with an MSVC compiler. 以下代码适用于GCC编译器,但它不适用于MSVC编译器。 I get the error 我收到了错误

Error (active) E0028 expression must have a constant value. 错误(活动)E0028表达式必须具有常量值。 The value of parameter "Length" (declared at line 5) cannot be used as a constant 参数“Length”的值(在第5行声明)不能用作常量

  1. What is a nice way to do this with an MSVC compiler? 使用MSVC编译器执行此操作的好方法是什么? and
  2. Is there any nice reason for this difference? 这种差异有什么好的理由吗?

My code: 我的代码:

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

As it was pointed out in the comments, you should definitely use std::vector<int> . 正如评论中指出的那样,你绝对应该使用std::vector<int>

If you want the array to live only inside your function Print , you can declare a dynamic array on the stack using new . 如果您希望阵列仅在您的函数Print ,则可以使用new在堆栈上声明动态数组。 Be mindfull of memory usage, though, as Print could be called with a big number, and you would get a stack overflow (again, use vector to avoid that). 但请注意内存使用情况,因为可以使用大数字调用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;
}

EDIT : Here's the vector-based correct solution : 编辑:这是基于矢量的正确解决方案:

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

If you really want a dynamically allocated, fixed size array, use an std::unique_ptr instead of an std::vector. 如果你真的想要一个动态分配的固定大小的数组,请使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM