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

So, I would like to create an array in a function with the size given by the number included as a parameter. Here is an example:

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 } 

Even if the parameter is const int, it will not work. I would not want to use global constants and not use vectors. I'm just wondering how I learn C ++. I would like it to make the array size different every time the function is called. Is there a solution for this or should I create a const variable and an array before calling the function?

+6
source share
5 answers

Using the template function:

 template<std::size_t array_size> void temp_arr() { int temp_arr[ array_size ]; // ...work with temp_arr... } 

You can then call the function using this syntax:

 temp_arr<32>(); // function will work with a 32 int statically allocated array 

Note

Each call with a different value of array_size will create a new function.

+7
source

When you pass a value in this function, the value is not a constant. An array definition must be performed with a constant value. Although you used const int array_size , this only creates an integer, which is a constant inside the function. Therefore, in a sense, if you pass the value of a variable into a function, it takes it as a variable. Therefore, an error occurs. Yes, you must create a constant and pass it during the function call.

+2
source

You can use:

 int const size = 10; int array[size]; 

to create an array in C ++. However you cannot use

 void temp_arr ( const int array_size ) { int temp_arr[array_size]; } 

to create an array if the compiler does not support VLA as an extension. The standard does not support VLA.

The const qualifier in the argument type simply turns the const variable into a function - you cannot change its value. However, the value may not necessarily be determined at compile time.

For example, you can call a function using:

 int size; std::cout << "Enter the size of the array: "; std::cin >> size; temp_arr(size); 

Since a value cannot be necessarily determined at compile time, it cannot be used to create an array.

0
source

If you do not have a memory problem, let me tell you a simple way: -

  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]); } } 

I know this is not an ideal solution, but just an easy way for beginners.

0
source

You can use 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 } 
0
source

All Articles