How to initialize all members of an array to the same value?
#1
I'm currently working on a project where I need to initialize a very large array with the same value for each element. Memory usage is a consideration, and I want to initialize the array efficiently, without defaulting to a loop that sets each element individually. Typically, I would just use `memset()`, but I vaguely remember there might be a more idiomatic way to do this within the C language. Am I misremembering, or is there indeed a syntax that allows me to initialize an array to a specific value throughout its entirety?
The array I'm dealing with is quite sizable and looks something like this:

Code:
c
int largeArray[1000];

What I want to achieve is to initialize all elements of `largeArray` to, let's say, `5`. Using `memset()` would look a bit like this, but it’s suited for character arrays since it works on byte level:

Code:
// ...
memset(largeArray, 5, sizeof(largeArray));

This doesn't work as intended for integers since `memset()` will set each byte to `5` resulting in the actual integer values being misrepresented. I'm seeking a single-line shorthand or a more appropriate C language feature for this task. Suggestions?
Reply
#2
What you're looking for is the designated initializer feature of C99. It allows you to initialize an array with a default value without having to use a loop or `memset()`. Here's how you can apply it to your example:

Code:
c
int largeArray[1000] = {
    [0...999] = 5
};

This syntax tells the compiler to initialize all elements from index `0` to `999` inclusive to the value `5`. It's a convenient way to initialize array elements when declaring the array.
Reply
#3
I appreciate the suggestion. However, the designated initializer syntax seems unfamiliar to me as I typically code in C89 standard. Is this approach widely supported across most compilers? I need to maintain compatibility with various compilers and systems.
Reply
#4
Designated initializers are indeed part of the C99 standard. While most modern compilers do support this feature, if you're targeting environments that strictly conform to C89 or you’re unsure about the C99 support, it may be safer to use a loop or stick with `memset()` for character arrays. For integer arrays, you could use a static function that abstracts the initialization loop. Consider this piece of code:

Code:
c
void initIntArray(int * arr, int size, int value) {
    for (int i = 0; i < size; i++)
        arr[i] = value;
}
// Then you'd call it like this:
initIntArray(largeArray, 1000, 5);
Reply
#5
It's clear now that if C99 features are not an option, I would have to use a function like the one you provided. However, wouldn't a macro be more versatile since it can be inline and avoid function call overhead?
Reply
#6
A macro could indeed be used for this purpose. Bear in mind that macros don't have type checks and can lead to subtle bugs if not carefully written. Here's how you might implement such a macro:

Code:
c
#define INIT_ARRAY(arr, size, value) do {
    \
    for (int i_ = 0; i_ < (size); i_++)\
        (arr)[i_] = (value);\
} while (0)

Use this macro like so:

Code:
c
INIT_ARRAY(largeArray, 1000, 5);
Reply
#7
Thank you, for the macro example. It does seem like a good compromise. But let's assume C99 compatibility isn't an issue. Is the designated initializer approach the most efficient way both in terms of execution speed and memory usage for initialising large arrays in C?
Reply
#8
The designated initializer should be efficient since its handled at compile time. However, do note that for large arrays, the compiler might generate a considerable amount of code behind the scenes, which could affect your binary size. Execution speed would likely be comparable to a loop, but the real benefit is the syntactic cleanliness and possible compile-time optimizations. Always measure if performance is a critical concern.
Here's the complete working code with the designated initializer:

Code:
c#include <stdio .h>

int main() {
    int largeArray[1000] = {
        [0...999] = 5
    };
    // Optional: Code to verify the initialization
    for (int i = 0; i < 1000; i++) {
        printf("%d ", largeArray[i]);
    }
    return 0;
}

Remember to test and verify that any solution you choose works efficiently on your target systems.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)