[LCP] Circular Struct Definitions
Paul Gearon
gearon at ieee.org
Fri Mar 6 05:11:13 EST 2009
2009/3/2 Christopher Howard <choward at indicium.us>:
> I'm writing these structs to represent two ideas in my program: one is menu
> items and the other is menus (i.e., lists of menu items -- I call them
> "Bundles"). The problem is that I not only want menus to contain arrays of
> menu items, but I also want menu items to contain references to other menus.
> The purpose of this is to allow for "sub-menus", so that selecting a menu
> item takes the user to another menu.
>
> /* MY CODE START */
>
> typedef struct {
> char command[256];
> char key_assignment;
> char label[256];
> MenuItem_Bundle * sub_menu;
> } MenuItem;
>
> typedef struct {
> MenuItem * menuitem_array;
> MenuItem_Bundle * owning_menu;
> } MenuItem_Bundle;
>
> /* MY CODE END */
The problem here is that you've referred to your new types before
you've finished defining them, so the compiler doesn't know which
types you're talking about at that point.
The way around it is to identify that these types are structs, and use
this label when referring to the struct:
typedef struct {
char command[256];
char key_assignment;
char label[256];
struct mi_bindle * sub_menu;
} MenuItem;
typedef struct mi_bundle {
MenuItem * menuitem_array;
struct mi_bundle * owning_menu;
} MenuItem_Bundle;
Notice that only the second struct needs this label, since the
MenuItem is fully defined before you try to refer to it. Conversely,
the MenuItem_Bundle struct needs a label to refer to it ahead of the
declaration (the sub_menu field of MenuItem), and within it's own
definition (the menuitem_array field).
Regards,
Paul
More information about the linuxCprogramming
mailing list