typedef struct {
double firstArray[3];
double secondArray[4][4];
bool thirdArray[2];
} myStruct;
I understand that we can initialize all values of an array to zero in one line using int myArray[10] = { 0 };
I have a function to initialize all elements of the arrays in myStruct to zero & false (for bool).
void initializeElementsOfStruct(myStruct* str)
{
str->firstArray[0] = 0.0;
str->firstArray[1] = 0.0;
str->firstArray[2] = 0.0;
...
}
Instead of the above or using for loops, how do I do it in one liners?
Edit: The struct may contain non primitive datatypes too.
Since you struct only consists of primitive types, you can set its entire memory representation to zero and should get the desired effect. (This may potentially overwrite padding bytes which you wouldn't be writing to in your member-wise approach, but that may actually be more efficient in the end.)
In C:
#include <string.h>
memset(str, 0, sizeof *str)
In C++:
#include <algorithm>
std::fill(reinterpret_cast<char*>(str),
reinterpret_cast<Char*>(str) + sizeof *str, 0);
The idiomatic solution, backward compatible with C89/90 is
void initializeElementsOfStruct(myStruct* str)
{
const myStruct ZERO = { 0 };
*str = ZERO;
}
For "stupid" compilers in it might make sense to declare ZERO
as static
(in performance-critical code).
In C99 you can simply do
void initializeElementsOfStruct(myStruct* str)
{
*str = (myStruct) { 0 };
}
A fairly equivalent C++ version (which is aware of C++ specific initialization semantics) will look as
void initializeElementsOfStruct(myStruct* str)
{
*str = myStruct();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With