How can I initialize a structure if one field in the structure is itself a structure?
            Asked
            
        
        
            Active
            
        
            Viewed 1,138 times
        
    3 Answers
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
        
- 219,201
- 40
- 422
- 469
- 
                    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
- 
                    4In 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,116
- 3
- 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,539
- 20
- 100
- 144
- 
                    2In 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
 
    