user39320
user39320

Reputation: 53

How to define a structure variable inside another structure?

I have 2 structures defined as follows :

typedef struct
{   
    char book_name[20] ;
    int book_id ;
    char author[20] ;
    char book_status[20];
}stlib ;

typedef struct
{
    char employee_name[20];
    int employee_id;
    char employee_dept[20];
    char emp_book_status[20];   
}stemp ;

How can I define a variable inside a structure pointing to another structure? Is this correct way ?

typedef struct
{   
    char book_name[20] ;
    int book_id ;
    char author[20] ;
    char book_status[20];   
}stlib ;

typedef struct
{
    char employee_name[20];
    int employee_id;
    char employee_dept[20];
    char emp_book_status[20];       
    struct stlib st; // is this correct ?
}stemp ;

Upvotes: 1

Views: 122

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your case, as we can see, stlib is a typedef to the unnamed struct and the definition of stlib appears before that of stemp, you need to change

 struct stlib st; // is this correct ?

to

stlib st; // this is correct

in stemp definition and you're good to go.


However, if by saying "inside a structure pointing to another structure", you meant a pointer, then you need to define st as a pointer, that's all.

Upvotes: 4

Related Questions