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?
3 answers. It is not possible to set a struct with NULL as it is declared. Fila f = NUll; error: invalid initializer. So cast% from% to NULL , which is not even a type in this code, or assign Fila to a primitive type variable is "wrong".
If a structure variable has static storage, its members are implicitly initialized to zero of the appropriate type. If a structure variable has automatic storage, its members have no default initialization.
You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
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;
The way to do such a thing when you have modern C (C99) is to use a compound literal.
a = (const struct x){ 0 };
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 the const
as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.
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