Link to home
Start Free TrialLog in
Avatar of gagajanice
gagajanice

asked on

struct within a struct

hi there,

i came across this struct code and i noticed that it is declaring itself inside it owns struct.

for example:
i have a struct called abc. and inside this abc struct, there is a declaration of struct abc with a next pointer pointing to it.

struct abc {
        char a[20];
        long b;
        struct abc * next;
}

Open in new window


may i know how is this possible and what is the purpose for this?

thanks in advance.
Avatar of phoffric
phoffric

This is not actually a struct within a struct (or nested struct). next is just a pointer to a struct abc. One common application for this is a single linked list. See, for example, the code in this question:
   https://www.experts-exchange.com/questions/23404167/Linked-list-help.html
SOLUTION
Avatar of DonConsolio
DonConsolio
Flag of Austria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gagajanice

ASKER

thank you everyone for the explaination.

phoffric, thanks for the url. very useful to me.
if you try using this:

struct abc {
        char a[20];
        long b;
        struct abc  next; //<-----without the pointer (*)
}

 you will get an error: 'next' uses undefined struct 'abc' since it is not declared.

Have a look at nested structs:
http://www.exforsys.com/tutorials/c-plus-plus/structure-in-c-part-ii.html