0

How to initialize a structure which contains other structure definitions inside it?.

Ex:

struct foo{
    struct foo1{
        int a;
        int b;
        int c;
    } abc;
} xyz;
lurker
  • 56,987
  • 9
  • 69
  • 103
Vishwanath gowda k
  • 1,675
  • 24
  • 26

2 Answers2

3

The easiest with modern C are designated initializers

struct foo xyz = { .abc = { .a = 56, } };

But beware that C doesn't have nested types, your foo1 is also a global type.

Generally people prefer to separate such type declaration, first the one for foo1 and then foo, from variable declarations and definitions.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
0

@JensGustedt shows the nice modern C way of doing it. The older school C way would be:

struct foo xyz = { { 1, 2, 3 } };   /* sets a, b, c to 1, 2, 3, respectively */
struct foo xyz = { { 1 } };         /* just sets the member "a" to 1
lurker
  • 56,987
  • 9
  • 69
  • 103