通过传递数组长度在函数内声明数组
Declaring an Array Inside a Function by Passing Its Length
我想要一个函数,它接受一个正整数,然后声明一个数组,初始化它并打印它。以下代码适用于 GCC 编译器,但不适用于 MSVC 编译器。我收到错误
错误(活动(E0028 表达式必须具有常量值。参数"Length"的值(在第 5 行声明(不能用作常量
- 使用 MSVC 编译器执行此操作的好方法是什么?
- 这种差异有什么好的理由吗?
我的代码:
#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();
}
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值