03-10-2024, 06:41 AM
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:
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:
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?
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?