views:

114

answers:

2

Hello,

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

Thank you.

A: 
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
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
+10  A: 

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
Optional in only where member `s` is fully initialised (i.e. all members), necessary if you want to only partially initialise the structure.
Clifford
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