Posts Tagged ‘struct initialization’

Structure Initialization (All Elements to 0) In C

Thursday, December 24th, 2009

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

A global or static structure is automatically initialized by all of its elements as 0 or null (In case of pointers). But if you want to initialize a local struct to this, what would you do? Many would say that would use a memset or calloc to set all the elements of that structure instance to 0. But this is incorrect as a null pointer might not be same as 0. So, the correct way to do this would be like:

struct a b = {0};

What this does is that it initializes the first element of the structure b to 0 (or null pointer if it is a pointer) and the rest of the elements are initialized like they would have been done if the structure was global or static.

© Safer Code | Structure Initialization (All Elements to 0) In C

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below