Re: Structures with variable length array known at compile time



aravind <aramosfet@xxxxxxxxx> writes:

Hi, I need to develop a menu system for a project of mine.
<snip>
struct menu
{
int n (no. of elements in menu);
char menu_items[20][q]; (This will contains the strings to be
displayed on the LCD, 20 characters and n lines
funcptr fptr; (Pointer to the corresponding menu function)
}
the array "menu_items" will always have 20 character strings but the
no. of them 'q' will differ from each menu screen. the no. of strings
will be defined in "int n".

This looks like homework (usually called coursework here in the UK) so
I am reluctant to post code. I will point out a couple of things...

You have the array the wrong what round -- what you wrote is an array
of 20 arrays of q characters each.

If the strings are to be 20 characters, it is better to use 21
character arrays and always have a null at the end. I.e. always keep
a proper string. If memory if very tight you can avoid this, but the
coding gets much more fiddly.

I will be using this struct to implement
const structs which i will be defining with all the menu screen
information.
From googling around i found variable length arrays cannot be
implemented with in structures. I also found that the structure size
should be known at compile time(i dont want to use malloc). My menu
items will be known at compile time. how do i implement this?

One way is to have a pointer to an array. These are a little odd, but
you have function pointers so array pointer are only a small step
away! Define the string array separately and then point to in when
you initialise the menu struct.

--
Ben.
.



Relevant Pages

  • Re: two dimensional arrays passed to functions
    ... > array and then send it down as a single dimmensional array. ... x is an array of char pointers. ... to a pointer to the first element of this array, ... need to copy the strings and not just assign pointers to them). ...
    (comp.lang.c)
  • Re: low-level pointer vs. array question
    ... that the array version is indeed superiour for my purposes. ... memory for pointer variables. ... Note that "it allocates memory only for the strings" ...
    (comp.lang.c)
  • Re: fast stable sort
    ... rather than isolating it in a separate array. ... It lumps an extra pointer in with the only one ... Building a linked list does not constitute using Oextra space. ... strings and linking the strings into an order. ...
    (comp.programming)
  • Re: char *arr[n] Vs. char **arr
    ... since the number of small strings is not ... the array format[], and copy the token to that address. ... The malloc statement gives a segfault. ... makes an integer from pointer" etc.. ...
    (comp.lang.c)
  • Re: char *arr[n] Vs. char **arr
    ... since the number of small strings is not ... the array format[], and copy the token to that address. ... The malloc statement gives a segfault. ... makes an integer from pointer" etc.. ...
    (comp.lang.c)