Noob question: Reset Struct Variables

Hello,

I would like to reset all of the variables within a struct object. So for example:

struct LotsaFloats
{
float a, b, c, d, e, f, g
} Assignment1, Assignment2;

Then code goes forth utilizing Assignment1.a and Assignment1.g etc...

Now I want to reset all values for Assignment1 to 0. How do I do that?

I tried:
LotsaFloats Assignment1 = { 0 };

This did not work.

However, individually doing the following:
Assignment1.a = 0;
Assignment1.b = 0;
etc...

DOES work. But this is unwieldy. Suggestions?
Use memset:

memset(&Assignment1, 0, sizeof(Assignment1))
Some suggestion ( open to criticism :o) )

1) Write a function that sets each variable to 0 and call it for the structure you have created.

2) Instead of using individual names for each float, create an array and use a for loop to initialise each element to 0.

3) (maybe MS specific) use ZeroMemory() function on a pointer to your structure?
http://www.cplusplus.com/forum/general/21822/
Or give your struct a default constructor which resets all the variables, and then use that.
Awesome, thanks for the answers
My input:

1) memset is fine as long as your struct is a POD struct. As soon as you add a complex type (like a string) memset will cause your program to explode. Since this isn't "future proof" I would recommend against it (you might want to add a string later -- and if you do you'll have to go back and change all the memsets in your program)

2) ZeroMemory is just a macro that calls memset. They're exactly the same.

3) A combination of Mooce's #1 suggestion and Xander's suggestion is what I recommend. Write a function that resets/zeros the struct, then make a default ctor that calls that function.

4) Mooce's #2 suggestion is also good if applicable. Although I would still put the resetting in a function.
Thanks for the clarification. Xander314 could you provide an example of how to define and call this constructer within my struct? Thanks
oh wait I got it.

struct LotsaFloats
{
float a, b, c, d, e, f, g
LotsaFloats()
{
a = 0; b = 0; c = 0; etc...
}
} Assignment1, Assignment2;

then I called using:

Assignment1 = LotsaFloats();
Yes, that's the right kind of thing :)
There is no need to do "Assignment1 = LotsaFloats(); "
The moment the variable Assignment1 is created, it is going to call the constructor, which is going to set all the values to zero as specified in the constructor.
Topic archived. No new replies allowed.