如何在C中将静态数组的所有元素重置为0

1 c arrays static

我在c中定义了一个静态数组,如下所示:

typedef struct
{
int a;
int b;
int c;
int d;
} Hello;

static Hello hello[6] = {{0}}; 
Run Code Online (Sandbox Code Playgroud)

然后在某些时候我需要将这个静态数组中每个元素的所有属性重置为0; 这该怎么做?

unw*_*ind 6

你需要使用memset():

#include <string.h>
memset(hello, 0, sizeof hello);
Run Code Online (Sandbox Code Playgroud)

请注意,这只能起作用,因为"所有位0"是将int变量设置为0 的非常安全的假设.如果hello包含例如floats或指针,则该假设根本不存在,您将不得不进行手动循环.