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?
Better than all above is ever to use Standard C specification for struct initialization:
Here are all bits zero (ever).
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:
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:
The way to do such a thing when you have modern C (C99) is to use a compound literal.
This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it
static
. If you use theconst
as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.I believe you can just assign the empty set (
{}
) to your variable.In C, it is a common idiom to zero out the memory for a
struct
usingmemset
:Technically speaking, I don't believe that this is portable because it assumes that the
NULL
pointer on a machine is represented by the integer value 0, but it's used widely because on most machines this is the case.If you move from C to C++, be careful not to use this technique on every object. C++ only makes this legal on objects with no member functions and no inheritance.
You can use
memset
with the size of the struct: