Initialize/reset struct to zero/null

2019-01-05 09:24发布

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

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.

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

8条回答
孤傲高冷的网名
2楼-- · 2019-01-05 10:21
 struct x myX;
 ...
 memset(&x, 0, sizeof(myX));
查看更多
甜甜的少女心
3楼-- · 2019-01-05 10:26

If you have a C99 compliant compiler, you can use

mystruct = (struct x){0};

otherwise you should do what David Heffernan wrote, i.e. declare:

struct x empty = {0};

And in the loop:

mystruct = empty;
查看更多
登录 后发表回答