簡體   English   中英

通過傳遞函數長度來聲明函數內部的數組

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

我想要一個帶正整數的函數,然后聲明一個數組,初始化它並打印它。 以下代碼適用於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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM