### Question 1.14

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 the `NODEPTR` example is that the typedef has not been defined at the point where the `next` field is declared. To fix this code, first give the structure a tag (```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

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

    	typedef struct node *NODEPTR;

and there are at least three other equivalently correct ways of arranging it.

A similar problem, with a similar solution, can arise when attempting to declare a pair of typedef'ed mutually referential structures.

See also question 2.1.

References: K&R1 Sec. 6.5 p. 101
K&R2 Sec. 6.5 p. 139
ANSI Sec. 3.5.2, Sec. 3.5.2.3, esp. examples
ISO Sec. 6.5.2, Sec. 6.5.2.3
H&S Sec. 5.6.1 pp. 132-3

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1995 // mail feedback