将结构初始化/重置为零/空 [英] Initialize/reset struct to zero/null
问题描述
struct x {
char a[10];
char b[20];
int i;
char *c;
char *d[10];
};
我正在填充这个结构,然后使用这些值.在下一次迭代中,我想在开始重用之前将所有字段重置为 0
或 null
.
I am filling this struct and then using the values. On the next iteration, I want to reset all the fields to 0
or null
before I start reusing it.
我该怎么做?我可以使用 memset
还是我必须通过所有成员然后单独做?
How can I do that? Can I use memset
or I have to go through all the members and then do it individually?
推荐答案
使用初始值定义结构体的 const 静态实例,然后在您想重置它时简单地将此值分配给您的变量.
Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.
例如:
static const struct x EmptyStruct;
这里我依靠静态初始化来设置我的初始值,但是如果你想要不同的初始值,你可以使用结构初始化器.
Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.
然后,每次循环你都可以写:
Then, each time round the loop you can write:
myStructVariable = EmptyStruct;
这篇关于将结构初始化/重置为零/空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!