prev up next   top/contents search

comp.lang.c FAQ list · Question 1.14

Q: 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?


A: 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 [footnote] 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 typedef name involving struct node even though struct node has not been completely defined yet; this you're allowed to do.[footnote] )

Finally, here is a rearrangement incorporating both suggestions:

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

	typedef struct node *NODEPTR;

(It's a matter of style which method to prefer; see section 17.)

See also questions 1.15 and 2.1.

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


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North