初始化一个结构体中的结构体

4

如果我在C中有一个结构体,其中包含一个整数和一个数组,如何将整数初始化为0并将数组的第一个元素初始化为0,如果该结构体是另一个结构体的成员,以便对于另一个结构体的每个实例,整数和数组都具有这些初始化值?


4
最好提供一个代码示例来说明您的问题... - Agnius Vasiliauskas
好文章推荐:C和C++:自动结构的部分初始化 - Alok Save
5个回答

7

对于嵌套结构体,可以进行嵌套初始化,例如:

typedef struct {
    int j;
} Foo;

typedef struct {
    int i;
    Foo f;
} Bar;

Bar b = { 0, { 0 } };

3

我希望这个示例程序能够对你有所帮助...

#include <stdio.h>

typedef struct
{
        int a;
        int b[10];
}xx;

typedef struct
{
        xx x1;
        char b;
}yy;

int main()
{

yy zz = {{0, {1,2,3}}, 'A'};


printf("\n %d  %d  %d %c\n", zz.x1.a, zz.x1.b[0], zz.x1.b[1], zz.b);

return 0;
}

yy zz = {{0, {0}}, 'A'};将初始化数组b[10]的所有元素为0。

像@unwind建议的那样,在C中,所有创建的实例都必须手动初始化。这里没有构造函数机制。


1
在C语言中,您仍然可以使用构造函数/析构函数,缺点是您必须显式调用它们,它们不会像具有内置面向对象支持的语言中那样自动调用。请参见我的答案以获取示例。 - Lundin
1
@Lundin 谢谢。但是mystruct_construct()需要为每个实例调用,对吗? - Jeyaram

1

您可以使用 {0} 对整个结构进行 0 初始化。

例如:

typedef struct {
  char myStr[5];
} Foo;

typedef struct {
    Foo f;
} Bar;

Bar b = {0}; // this line initializes all members of b to 0, including all characters in myStr.

1
有没有一种方法可以在 Bar 内部初始化 Foo? - Nathan Yeung
1
你是指 b.f = {0} 还是 b.f = someOtherF?否则,在 C 中没有构造函数,所以你无法为 f 实现默认初始化。 - yuklai

1

C语言没有构造函数,所以除非你在每种情况下都使用初始化表达式,即像这样编写:

my_big_struct = { { 0, 0 } };

为了初始化内部结构,您需要添加一个函数,并确保在所有实例化结构的情况下都调用它:

my_big_struct a;

init_inner_struct(&a.inner_struct);

1
使用“不透明类型”(也称为不完整类型)更安全、更优雅。这样调用者就无法访问结构体的私有成员变量。 - Lundin

1

这里是一个使用面向对象设计来完成类似任务的替代示例。请注意,此示例使用运行时初始化。

mystruct.h

#ifndef MYSTRUCT_H
#define MYSTRUCT_H

typedef struct mystruct_t mystruct_t;  // "opaque" type

const mystruct_t* mystruct_construct (void);

void mystruct_print (const mystruct_t* my);

void mystruct_destruct (const mystruct_t* my);

#endif

mystruct.c

#include "mystruct.h"
#include <stdlib.h>
#include <stdio.h>

struct mystruct_t   // implementation of opaque type
{
  int x; // private variable
  int y; // private variable
};


const mystruct_t* mystruct_construct (void)
{
  mystruct_t* my = malloc(sizeof(mystruct_t));

  if(my == NULL)
  {
    ; // error handling needs to be implemented
  }

  my->x = 1;
  my->y = 2;

  return my;
}

void mystruct_print (const mystruct_t* my)
{
  printf("%d %d\n", my->x, my->y);
}


void mystruct_destruct (const mystruct_t* my)
{
  free( (void*)my );
}

main.c

   int main (void)
   {
      const mystruct_t* x = mystruct_construct();

      mystruct_print(x);

      mystruct_destruct(x);

      return 0;
   }

您不一定需要使用malloc,也可以使用私有的、静态分配的内存池。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接