I apologize(thanks to @JaMiT) because misread your question.
In C++ number of rows and columns in a two dimensional array must be compile time constants. You are not allowed to use variable to set array dimension.
So if second dimension must be variable you could use std::vector or another mechanism to allocate/deallocate dynamic memory.
Here is my example with std::vector:
#include <vector>
using resizable_second_dim_array = std::vector<int> (&)[2];
void set_second_dimension(resizable_second_dim_array aArray,
std::size_t aNewDim)
{
for (auto & vec : aArray)
{
vec.resize(aNewDim);
}
}
int main()
{
std::vector<int> my_arr[2]{};
std::size_t secondDim = 10;
set_second_dimension(my_arr, secondDim);
//do something with my_arr
//...
//change second dimension
secondDim = 20;
set_second_dimension(my_arr, secondDim);
//do something with my_arr
//...
return 0;
}
As @Sebastian pointed out another option would be to use std::array:
#include <array>
#include <vector>
using resizable_second_dim_array = std::array<std::vector<int>, 2>;
void set_second_dimension(resizable_second_dim_array & aArray,
std::size_t aNewDim)
{
for (auto & vec : aArray)
{
vec.resize(aNewDim);
}
}
int main()
{
resizable_second_dim_array my_arr{};
std::size_t secondDim = 10;
set_second_dimension(my_arr, secondDim);
//do something with my_arr
//...
//change second dimension
secondDim = 20;
set_second_dimension(my_arr, secondDim);
//do something with my_arr
//...
return 0;
}
n? Also what value do you thinknwill be beforeint main()is executed? Remember that globals are initialized before main() starts and that even if your compiler supports the nonstandard VLA its size will not grow after it is initialized.nis involved? Which scope / what is a scope? What is a declaration?)