1

Given the following very basic function, how would I initialize arr to all random values, and how would I initialize arr to a set of given values, say the numbers 0-11?

void func() { static int arr[2][2][3]; } 

With my limited knowledge of static variables and C++ in general, I think that the static array needs to be initialized in one line, so when the function is called again, it does not get re-initialized. Basically, I want to say:

static int arr[2][2][3] = another_array

But this raises an error that 'another_array' is not an initializer list. I looked up initializer lists but they all included classes and other stuff I didn't understand. Is there any way to initialize this array? Any help is appreciated.

1 Answer 1

1

Technically if you try to assign the value of arr in a separate line, it will never be re-initialzied after the first time it was initialized. It will be re-assigned. But based on what you described, I assume that's the behavior you want to prevent.

So to initialized arr in the same line, what you could do is first create a function that will generate the desired number for you, then call that function many times during initializing arr:

 int gen_num() { // some code to return a random number for you... } void func() { // I reduced `arr` to a 2D array, to make the code shorter. Making it a 3D array basically works the same static int arr[2][3] = {{gen_num(), gen_num(), gen_num()}, {gen_num(), gen_num(), gen_num()}}; } 

Note, if you make arr an std::array instead of the C-style array, then you can actually build up an array in a separate function, then just return the new array from that function:

std::array<std::array<int, 3>, 2> create_array() { std::array<std::array<int, 3>, 2> result; // here you can assign each value separately result[0][0] = 20; result[2][1] = 10; // or use for loop freely as needed for(auto& arr : result) { for(auto& value : arr) { value = get_num(); } } return result; } void func() { // Basically the same as having `int arr[2][3]` static std::array<std::array<int, 3>, 2> arr = create_array(); } 
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you! Is there anyway not to enter in the numbers manually, because the actual array has hundreds of values?
Stuff like std::array<std::array<int, 3>, 2> result = { all values go here }; is possible.
Could std::array be a static array? Also, does that work for a large quantity of numbers, where it would be too many to input one-by-one?
@BanjoMan I've added how you can simply use a for-loop to assign the value in the std::array. Yes, it can static.
@BanjoMan "large quantity of numbers" - depends on how large you are looking for. It is bounded by the stack size, but it will definitely be fine for just a few thousand numbers.
|