Interview Questions

I can not seem to define a linked list successfully

C Interview Questions and Answers


(Continued from previous question...)

I can not seem to define a linked list successfully

I can't seem to define a linked list successfully. I tried
typedef struct {
char *item;
NODEPTR next;
} *NODEPTR;

but the compiler gave me error messages. Can't a structure in C contain a pointer to itself?

Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear.

The problem with this example is the typedef. A typedef defines a new name for a type, and in simpler cases you can define a new structure type and a typedef for it at the same time, but not in this case. A typedef declaration can not be used until it is defined, and in the fragment above, it is not yet defined at the point where the next field is declared.

To fix this code, first give the structure a tag (e.g. ``struct node''). Then, declare the next field as a simple struct node *, or disentangle the typedef declaration from the structure definition, or both. One corrected version would be:

typedef struct node {
char *item;
struct node *next;
} *NODEPTR;

You could also precede the struct declaration with the typedef, in which case you could use the NODEPTR typedef when declaring the next field, after all:
typedef struct node *NODEPTR;

struct node {
char *item;
NODEPTR next;
};

(In this case, you declare a new tyedef name involving struct node even though struct node has not been completely defined yet; this you're allowed to do.)
Finally, here is a rearrangement incorporating both suggestions:
struct node {
char *item;
struct node *next;
};

typedef struct node *NODEPTR;

(Continued on next question...)

Other Interview Questions