Structure Initialization (All Elements to 0) In C

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

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Reddit
  • Print this article!

Related posts

Tags: , ,

One Comment

  • Jay C. says:

    There was some discussion of this exact topic at my work recently. After looking it up in Harbison, Steele “C: A Reference Manual (5th Edition)”, and verifying against various recent and old versions of gcc, we’re convinced that the single 0 in the braces is not needed. If it looks cleaner to you, the following should work:

    struct a b = {};

Leave a Reply