Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
hari Avatar asked Jul 31 '11 19:07

hari


People also ask

Can you initialize a struct to NULL?

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".

Are struct members initialized to zero?

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.

Can you initialize in struct?

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.


2 Answers

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; 
like image 78
David Heffernan Avatar answered Sep 21 '22 21:09

David Heffernan


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.

like image 32
Jens Gustedt Avatar answered Sep 21 '22 21:09

Jens Gustedt