Initialize/reset struct to zero/null

Viewed 229177
struct x {
    char a[10];
    char b[20];
    int i;
    char *c;
    char *d[10];
};

I am filling this struct and then using the values. On the next iteration, I want to reset all the fields to 0 or null before I start reusing it.

How can I do that? Can I use memset or I have to go through all the members and then do it individually?

11 Answers

I asked a compiler engineer at work about which option is better (memset vs {0}). Instead of giving my an opinion he pointed me to Compiler Explorer. It's interesting to see how all three options compile out:

https://godbolt.org/z/bPfKeG9Yh

Here's a preview of the code:

// Type your code here, or load an example.
#include "string.h"

struct MyStruct {
    int age;
    int sin;
    char *name;
    int cats;
    char something[64];
};

const struct MyStruct empty_struct = {0};

int test() {
    struct MyStruct blah = {0};
    memset(&blah, 0, sizeof(blah));
    blah = empty_struct;

    blah.age = 99;
    blah.sin = 123456789;
}

The compiler makes different decisions on how to zero memory depending on the member types of the struct. Try commenting out something for example or choosing a non-x86 target.

Memset with NULL is dangerous function.

For C++ better by this way for most simple data structures >>

template<class T>
void Null_MyType(T &obj)
{
    constexpr T o_null = T{};
    obj = o_null;
}

debugger screenshot

Take a surprise from gnu11!

typedef struct {
    uint8_t messType;
    uint8_t ax;  //axis
    uint32_t position;
    uint32_t velocity;
}TgotoData;

TgotoData tmpData = { 0 };

nothing is zero.

Related