Home > Enterprise >  How to initialize a static array in C
How to initialize a static array in C

Time:04-13

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.

CodePudding user response:

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

  • Related