在C中初始化结构体中的数组

发布于 2024-10-30 14:30:46 字数 226 浏览 4 评论 0原文

struct myStruct
{   
    short int myarr[1000];//want to initialize all elements to 0
}

如何初始化数组?

我尝试在结构内执行 short int* myarr[1000]={0} 但这是错误的。我该怎么做?我不介意在实现文件中这样做。该结构包含在头文件中。

struct myStruct
{   
    short int myarr[1000];//want to initialize all elements to 0
}

How do I initialize the array?

I tried doing short int* myarr[1000]={0} inside the struct but it's wrong. How can I do this? I don't mind doing it in the implementation file. This struct is contained in a header file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

彡翼 2024-11-06 14:30:46

使用通用初始值设定项:{0}

通用初始化器适用于任何东西,并将元素初始化为正确的 0(对于指针,NULL,对于整数,0,对于双精度数,0.0,.. .):

struct myStruct example1 = {0};
struct myStruct example2[42] = {0};
struct myStruct *example3 = {0};

编辑动态分配的对象。

如果您要动态分配内存,请使用 calloc 而不是 malloc

p = malloc(nelems * sizeof *p); /* uninitialized objects; p[2] is indeterminate */
q = calloc(nelems, sizeof *q);  /* initialized to zero; q[2] is all zeros */

对于 realloc(以及可能的其他情况),您需要 memset

Use the universal initializer: {0}.

The universal initializer works for anything and initializes the elements to the proper 0 (NULL for pointers, 0 for ints, 0.0 for doubles, ...):

struct myStruct example1 = {0};
struct myStruct example2[42] = {0};
struct myStruct *example3 = {0};

Edit for dynamically allocated objects.

If you're allocating memory dynamically use calloc rather than malloc.

p = malloc(nelems * sizeof *p); /* uninitialized objects; p[2] is indeterminate */
q = calloc(nelems, sizeof *q);  /* initialized to zero; q[2] is all zeros */

With realloc (and possibly other situations) you need to memset.

临走之时 2024-11-06 14:30:46

如果它是在函数之外(而不是在堆栈上)声明的,则整个结构将在编译时归零。

否则,您可以在声明后使用memset。

If it is declared out of a function (not on the stack), the whole struct will be zeroed at compile time.

Otherwise, you can use memset after declaring it.

握住你手 2024-11-06 14:30:46

只需使用 {0} 初始化该结构的实例,这也会将您的数组归零。或者,按照 NKCSS 的演示使用 memset。

Just initialize an instance of the struct with {0}, this will zero your array as well. Alternatively, use memset as NKCSS demonstrates.

万劫不复 2024-11-06 14:30:46

int 不是引用类型,它们在为结构分配内存后不会被初始化吗?

你可以这样做:
memset(&myStruct, 0, sizeof(myStruct));

int's arn't reference types, don't they get initialized after allocating memory for your structure?

You could just do this:
memset(&myStruct, 0, sizeof(myStruct));

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文