Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C > Re: struct decl...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 6 Topic 24768 of 28006
Post > Topic >>

Re: struct declaration (silly question)

by Ben Pfaff <blp@[EMAIL PROTECTED] > Mar 2, 2008 at 05:38 PM

Marcin Kasprzak <no@[EMAIL PROTECTED]
> writes:

> Silly question - what is the most elegant way of compiling a code
similar
> to this one?
> [code for mutually referential structures]

Refer to the C FAQ.

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?

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 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; ISO
	Sec. 6.5.2, Sec. 6.5.2.3; H&S Sec. 5.6.1 pp. 132-3.
-- 
"I've been on the wagon now for more than a decade. Not a single goto
 in all that time. I just don't need them any more. I don't even use
 break or continue now, except on social occasions of course. And I
 don't get carried away." --Richard Heathfield
 




 6 Posts in Topic:
struct declaration (silly question)
Marcin Kasprzak <no@[E  2008-03-03 01:12:20 
Re: struct declaration (silly question)
Peter Nilsson <airia@[  2008-03-02 17:38:54 
Re: struct declaration (silly question)
Ben Pfaff <blp@[EMAIL   2008-03-02 17:38:20 
Re: struct declaration (silly question)
William Pursell <bill.  2008-03-02 20:51:00 
Re: struct declaration (silly question)
William Pursell <bill.  2008-03-02 20:54:55 
Re: struct declaration (silly question)
Marcin Kasprzak <no@[E  2008-03-03 09:50:50 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Fri Nov 21 12:27:17 CST 2008.