在C++函数中创建数组,而不使用全局变量

Create an array in a function in C++ without a global variable

本文关键字:全局变量 数组 C++ 函数 创建      更新时间:2023-10-16

所以我想在一个函数中创建一个数组,其大小由一个作为参数的数字设置。下面是一个示例:

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
}