So I would like to create an array in a function with the size set by a number coming in as the 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 a const int, it will not work. I would like to not use a global const and not use vectors. I am just curious as I am learning C++. I would like for it to make it so that the array size is different each time the function is called. Is there a solution to this or am I to create a const variable and the array before the function is called?
Global Arrays in C 1 These functions work only with particular array (s) and cannot be used for performing similar operations on other... 2 As the arrays can be modified from any part of the program, debugging such programs is more difficult. However, this... More ...
However, the array can be declared without initialization in the global scope and then assigned values in the function scope (or other scopes), as the following program shows: The global scope has the declaration “char ch [5];”. The assignment of the values has been done in the C++ main () function. The C++ main function is still a function.
The C++ main function is still a function. These are the rules on how to use an array in the global scope, function scope and nested local scope (or any other scope): 1. An array can be declared with the initialization of practical values in one statement in any scope (global, function, nested local scope).
Important Note: Arrays in C are passed as reference not by value. Which means any changes to array within the function will also persist outside the function. How to return single dimensional array from function?
Using a 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 with this syntax:
temp_arr<32>(); // function will work with a 32 int statically allocated array
Note
Every call with a different value of array_size
will instantiate a new function.
When you pass a value in this function, the value is not a constant. Defining an array must be done with a constant value. Although you have used const int array_size
, that only creates an integer that is constant within the function. So in a way, if you pass a variable value in the function, it takes it as a variable. Thus it produces an error. Yes, you are to create a constant and pass it during the function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With