[英]How to defaultly set variable inside C struct
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:我在 C 中有一个结构,需要将其中的一个值设置为 1。这意味着对于从该结构创建的所有新结构,阶段变量应该自动为 1。到目前为止,我已经尝试过:
new_struct->stage = 1;
and和
struct new_struct {
stage = 1;
}
but none of these actually work.但这些都没有真正起作用。 Is there a way to do this properly?
有没有办法正确地做到这一点?
Define an init_struct
function, and call it religiously for every new_struct
you allocate.定义一个
init_struct
function,并为您分配的每个new_struct
虔诚地调用它。 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:如果你分配一个普通的
new_struct
变量,通过调用init_struct
来初始化它,传递一个指向它的指针:
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
:如果您调用
malloc
来获取指向 memory 的指针以获得全新的new_struct
,则将该指针传递给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.我展示的
init_struct
function 仅初始化stage
成员,因为这就是您所说的您担心的问题。 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
:通常,确保结构中的所有内容都干净地初始化为零也是一个好主意,您可以通过添加对
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.) (理论上,
memset
调用可能不足以分配指针或浮点类型的结构成员,但这是一个相当深奥的问题,在您今天可能使用的任何机器上, memset
调用就足够了。)
You could wrap the struct declaration and initialization into a function:您可以将结构声明和初始化包装到 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?
难道没有更好的方法来处理你试图解决的任何问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.