Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize members of a struct to zero via the struct pointer

Tags:

c++

arrays

c

struct

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.

like image 344
ontherocks Avatar asked Dec 20 '22 00:12

ontherocks


2 Answers

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);
like image 188
Kerrek SB Avatar answered Dec 24 '22 02:12

Kerrek SB


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();
}
like image 30
AnT Avatar answered Dec 24 '22 02:12

AnT