在C++函数中创建数组,而不使用全局变量
Create an array in a function in C++ without a global variable
所以我想在一个函数中创建一个数组,其大小由一个作为参数的数字设置。下面是一个示例:
void temp_arr ( const int array_size ) {
int temp_arr[array_size]; //ERROR array_size needs to be a constant value
//Then do something with the temp arr
}
即使参数是 const int,它也不起作用。我不想使用全局常量,也不想使用向量。我只是好奇,因为我正在学习C++。我希望它使每次调用函数时数组大小都不同。是否有解决方案,或者我是否要在调用函数之前创建一个 const 变量和数组?
使用模板函数:
template<std::size_t array_size>
void temp_arr()
{
int temp_arr[ array_size ];
// ...work with temp_arr...
}
然后,可以使用以下语法调用该函数:
temp_arr<32>(); // function will work with a 32 int statically allocated array
注意
每个具有不同值 array_size
的调用都将实例化一个新函数。
在此函数中传递值时,该值不是常量。定义数组必须使用常量值来完成。尽管您使用了 const int array_size
,但这只会创建一个在函数中常量的整数。因此,在某种程度上,如果您在函数中传递变量值,它会将其视为变量。因此,它会产生错误。是的,您要创建一个常量并在函数调用期间传递它。
如果你没有记忆问题,让我告诉你一个简单的方法:-
void temp_arr ( const int array_size )
{
//lets just say you want to get the values from user and range will also be decided by the user by the variable array_size
int arr[100]; //lets just make an array of size 100 you can increase if according to your need;
for(int i=0; i<array_size ; i++)
{
scanf("%d",&arr[i]);
}
}
我知道这不是一个完美的解决方案,而只是初学者的简单方法。
您可以使用:
int const size = 10;
int array[size];
以在C++中创建数组。但是,您不能使用
void temp_arr ( const int array_size ) {
int temp_arr[array_size];
}
以创建数组,除非编译器支持 VLA 作为扩展。该标准不支持 VLA。
参数类型中的const
限定符只是使变量在函数中const
- 不能修改其值。但是,该值不一定在编译时确定。
例如,您可以使用以下命令调用该函数:
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;
temp_arr(size);
由于该值不一定在编译时确定,因此不能用于创建数组。
你可以
使用 std::unique_ptr:
void temp_arr(int array_size)
{
auto temp_arr = std::make_unique<int[]>(array_size);
// code using temp_arr like a C-array
}
相关文章:
- 如何在C++中动态分配全局字符数组中的类实例?
- c++ 中的别名变量数组
- 使用类的其他成员变量定义类的成员变量数组
- C++全局常量数组:是否保证合并(优化)到一个副本中
- 可视化 如何在C++中使用复杂变量数组
- 如何 for 循环类变量数组
- C 中的全局字符串数组
- 具有可变大小的C++全局队列数组
- 试图在C++中的两个类文件之间使用全局2D数组
- 按变量数组中的列将一组整数从文本文件读入
- 运行时C++中的变量数组维度
- 在函数中创建值,然后将指针保存在全局指针数组中的值上
- C++变量数组
- C++中的全局静态数组
- 声明和初始化全局 2D 数组
- 将变量(数组类型)从函数传递到"main"范围类型:标准::tr1::match_results<标准::字符串::const_iterator>
- 在堆栈上使用大变量/数组的缺点
- 如何在继承类中创建父类变量数组作为私有成员
- 如何创建一个类变量数组
- 如何在c++中通过地址传递将scanf字符串传递给全局字符数组