Alex Rivera | Logout

Why can't a struct have a member that is of the same type as itself?

Asked 2013-05-24T18:42:04.833
9

I'm stuck on understanding what's happening with this struct (from C for Programmers a Deitel book).

The book says, "A structure cannot contain an instance of itself. For example, a variable of type struct employee cannot be declared in the definition for struct employee. A pointer to struct employee, however, may be included."

It then gives the following example:

struct employee2 {
   char firstName[ 20 ];

   char lastName[ 20 ];

   unsigned int age;

   struct employee2 *ePtr;
};

I don't understand what this is doing, and I don't understand the reference to struct employee without the 2.

How does struct employee2 *ePtr know about struct employee or am I off basis here?

Edit
Report

1 Answer

3

you can not put a whole struct inside of itself because it would be infinitely recursive.

but you can put the address of another instance of a struct inside of a struct; which is what a pointer is... an address the size of SomeStruct* is always the same, so the compiler knows how much memory to make for one instance of the struct.

answered 2013-05-24T18:45:05.653

Your Answer