tags:

views:

43

answers:

2

I have a long C (not C++) struct. It is used to control entities in a game, with position, some behavior data, nothing flashy, except for two strings. The struct is global.

Right now, whenever an object is initialized, I put all the values to defaults, one by one

myobjects[index].angle = 0; myobjects[index].speed = 0;

like that. It doesn't really feel slow, but I am wondering if copying a "template" struct with all values set to the defaults is faster or more convenient.

So, to sum up into two proper questions: Is it faster to copy a struct instead of manually setting all the data? What should I keep in mind about the malloc-ed memory for the strings?

+2  A: 

"More convenient" is likely the more important part.

struct s vs[...];
...
// initialize every member to "default"
// but can't use in normal assignment
struct s newv = {0};
vs[...] = newv;

Or hide the "initialization details" behind an init-function (or a macro, if you dislike maintainable code :-)

struct s* init_s (struct s* v, ...) { /* and life goes on */ }
pst
+1  A: 

You may use this sequence:

memset(myobjects+index,0,sizeof(myobjects[0]);

if all you need is to set all members to zero

Beware: if a particular member is pointer, it will be set to NULL

Nelu Cozac

Nelu Cozac
Nathon