Search code examples
cstructinitialization

Initialize/reset struct to zero/null


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?


Solution

  • Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.

    For example:

    static const struct x EmptyStruct;
    

    Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.

    Then, each time round the loop you can write:

    myStructVariable = EmptyStruct;