Question: C string/structure confusion

William P. Kaufman wkaufman at oracle.oracle.com
Sat Apr 7 08:15:26 AEST 1990


In article <78932 at tut.cis.ohio-state.edu> <waylonis at cis.ohio-state.edu> writes:
>typedef struct menu_struct
>{
>	int	num_items;
>	char	**item; 	/* this may be wrong, but I want a arbitrary
>				   number of items of arbitrary length */
>} menu_td;
>
>menu_td  menu[5];		/* want 5 menus */
>
>	menu[0].item[0] = "Item0";

	Don't tell me: the compiler accepts it, but it pukes at run-time.

	OK, the trick I've found to dealing with obscure structures is to strip
down what you want, and figure out its type.

	menu is an array of menu_td, so menu[0] is valid, and it's a menu_td.
	menu[0].item then is valid, and its a (char **), so that assignment
_looks_ fine.  But, since it's a _pointer_ and not an _array_, menu[0].item
points to random space: it needs to be allocated!

	    menu[0].item =
		(char **)malloc( (size_of_item_array) * (sizeof(char *)) );

	Can't stress strongly enough--if
		a) you need a list of stuff (this is true for any type)
		b) either the number of stuff is constant, or it's range is
			known and is small
	and	c) you don't need off-the-cuff assignment of the stuff pointe

typedef struct menu_struct
{
	int	num_items;
	char	*item[MAXITEM];
} menu_td;

If you've got a good idea of how many items you'll have (say, within a tenth
of the actual number), and you don't have any cases where you might want to
assign a pre-assigned array of strings to item, this might be better.  Hey,
you see how many posts we get on this one subject alone?

Practice safe programming!  Even if it might cause you to waste a couple of
megs of memory,...memory's cheap!  But, I'm not.

			-- Bill Kaufman.
			{...}!hplabs!oracle.com!wkaufman
			.sig under construction



More information about the Comp.lang.c mailing list