Structure initialization and clearing

R

Roubles

Hi All,

Quick question; what is the difference between initializing and
clearing a structure like this:

mystruct_t a = {0};


and initializing and clearing it like this:

mystruct_t a;

memset(a, 0, sizeof(mystruct_t));

TIA,
Roubles
 
K

Kenneth Brody

Roubles said:
Hi All,

Quick question; what is the difference between initializing and
clearing a structure like this:

mystruct_t a = {0};

and initializing and clearing it like this:

mystruct_t a;

memset(a, 0, sizeof(mystruct_t));

In practice, probably not much.

However, suppose the first element of the struct were a pointer, and
you are on a system where a NULL pointer is not all-bits-zero.

Also, my understanding is that _all_ entries will be set to their zero
representation, which may not be all-bits-zero. (For example, a "double"
value.)
 
D

Default User

Roubles said:
Hi All,

Quick question; what is the difference between initializing and
clearing a structure like this:

mystruct_t a = {0};

This sets each member of the structure to the equivalent of 0 for the
type. You can only intitialize this way, not assign.
and initializing and clearing it like this:

mystruct_t a;

memset(a, 0, sizeof(mystruct_t));


This sets the whole thing to all-bits 0. For some things like floating
point numbers or pointers, this could be the wrong thing.



Brian Rodenborn
 
J

Joe Wright

Roubles said:
Hi All,

Quick question; what is the difference between initializing and
clearing a structure like this:

mystruct_t a = {0};


and initializing and clearing it like this:

mystruct_t a;

memset(a, 0, sizeof(mystruct_t));

TIA,
Roubles

The first is an initialization the compiler does for you and the
second is one you do yourself. You know that. What is the real
question? As an aside, I note that the prototype..

void *memset(void *buffer, int ch, size_t num);

...suggests to me..

memset(&a, 0, sizeof a);

...but of course, it's just style, right?
 
J

Joe Wright

Roubles said:
Hi All,

Quick question; what is the difference between initializing and
clearing a structure like this:

mystruct_t a = {0};


and initializing and clearing it like this:

mystruct_t a;

memset(a, 0, sizeof(mystruct_t));

TIA,
Roubles

Note that a is a structure, not a pointer. You need &a to take its
address for memset().
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,372
Latest member
LucretiaFo

Latest Threads

Top