简体   繁体   中英

Initializing a Struct of a Struct

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

Initialisers can be nested for nested structs, eg

typedef struct {
    int j;
} Foo;

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

Bar b = { 0, { 0 } };

I hope this sample program helps....

#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'}; will initialize all the elements of array b[10] will be set to 0.

Like @unwind suggestion, In C all instances created should initialized manually. No constructor kind of mechanism here.

You can 0-initialize the whole struct with {0}.

For example:

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.

C doesn't have constructors, so unless you are using an initializer expression in every case, ie write something like

my_big_struct = { { 0, 0 } };

to initialize the inner structure, you're going to have to add a function and make sure it's called in all cases where the structure is "instantiated":

my_big_struct a;

init_inner_struct(&a.inner_struct);

Here is an alternative example how you would do things like this with object-oriented design. Please note that this example uses runtime initialization.

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;
   }

You don't necessarily need to use malloc, you can use a private, statically allocated memory pool as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM