I have a struct in C, and need to set a value inside it to 1. This means that for all new structs created off that struct, the stage variable should be automatically 1. So far I have tried:
new_struct->stage = 1;
and
struct new_struct {
stage = 1;
}
but none of these actually work. Is there a way to do this properly?
CodePudding user response:
Define an init_struct
function, and call it religiously for every new_struct
you allocate. It might look like this:
void init_struct(struct new_struct *nsp)
{
nsp->stage = 1;
}
If you allocate an ordinary new_struct
variable, initialize it by calling init_struct
, passing a pointer to it:
struct new_struct ns;
init_struct(&ns);
If you call malloc
to get a pointer to memory for a brand-new new_struct
, pass that pointer to init_struct
:
struct new_struct *p = malloc(sizeof(struct new_struct));
if(p != NULL) init_struct(p);
The init_struct
function I've shown only initializes the stage
member, since that's what you said you were worried about. Usually it's also a good idea to make sure that everything in the structure is cleanly initialized to zero, which you can do by adding a call to memset
:
void init_struct(struct new_struct *nsp)
{
memset(nsp, 0, sizeof(*nsp));
nsp->stage = 1;
}
(Theoretically that memset
call might not be adequate for allocating structure members of pointer or floating-point types, but this is a rather esoteric concern, and on any machine you're likely to use today, the memset
call will be sufficient.)
CodePudding user response:
You could wrap the struct declaration and initialization into a function:
struct new_struct init_struct(void)
{
struct new_struct s = { .stage = 1 };
return s;
}
or a macro:
#define NEW_STRUCT(s) struct new_struct s = { .stage = 1 }
and use that everywhere you would otherwise use
struct s v;
like
struct new_struct v = init_struct();
// or
NEW_STRUCT(v1);
I would however question why you would need a bunch of structs that all have the same value in one element first place? Isn't there a better way to deal with whatever problem you try to solve with that?