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
  • 55,215
  • 8
  • 64
  • 98
Vishwanath gowda k
  • 1,527
  • 21
  • 25

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
  • 74,635
  • 5
  • 99
  • 170
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
  • 55,215
  • 8
  • 64
  • 98