初始化/复位结构零/空 [英] Initialize/reset struct to zero/null

查看:139
本文介绍了初始化/复位结构零/空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct x {
    char a[10];
    char b[20];
    int i;
    char *c;
    char *d[10];
};

我填充这个结构,然后使用这些值。在接下来的迭代中,我想我才开始重新使用它来重置所有字段 0

我怎样才能做到这一点?我可以用 memset的或我必须要经过所有成员,然后实现它单独?

How can I do that? Can I use memset or I have to go through all the members and then do it individually?

推荐答案

定义结构的常量静态实例与初始值,然后每当你想重新设置这个值只分配给您的变量。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆