13

How can I initialize a structure if one field in the structure is itself a structure?

Cœur
  • 34,719
  • 24
  • 185
  • 251
0xAX
  • 19,709
  • 24
  • 113
  • 202

3 Answers3

14

You need to use more braces (actually, they're optional, but GCC makes a warning these days). Here's an example:

struct s1 { int a; int b; };
struct s2 { int c; struct s1 s; };

struct s2 my_s2 = { 5, { 6, 3 } };
Carl Norum
  • 210,715
  • 34
  • 410
  • 462
  • Optional in only where member `s` is fully initialised (i.e. all members), necessary if you want to only partially initialise the structure. – Clifford Jul 05 '10 at 09:09
  • 4
    In C99 you may use the following notation which is easier to maintain and to read: `struct s2 my_s2 = { .c = 5, .s = { .a = 6, .b = 3 } };` – Jens Gustedt Jul 05 '10 at 16:40
1

Nesting of structure

You can initialize a structure if one field in the structure is itself a structure

struct add{
    int house;
    char road;
};
struct emp{
    int phone;
    struct add a;
};

struct emp e = { 123456, 23, "abc"};
printf("%d %d %c",e.phone,e.a.house,e.a.road);
Community
  • 1
  • 1
Varun Chhangani
  • 1,068
  • 2
  • 13
  • 18
0
struct A
{
int n;
}

struct B
{
A a;
} b;

You can initialize n by the following statement. Is this what you are looking for.

b.a.n = 10;
ckv
  • 10,125
  • 19
  • 96
  • 139
  • 2
    In the terms used to define the language, that is an example of *assignment* rather than *initialisation*. In this context an initialiser is used only at declaration of an object. – Clifford Jul 05 '10 at 09:06