You should declare menu
as a pointer to [some array of] pointer strings:
char**menu;
You need to know the number of menu entries. So declare also
size_t nb_menu;
and have some way to compute it at runtime. (I leave that up to you, but you cannot use sizeof
which is a compile-time thing).
You then allocate in the heap, using calloc(3), that array:
menu = calloc (nb_menu+1, sizeof(char*));
if (!menu) { perror("calloc menu"); exit (EXIT_FAILURE); };
I'm doing nb_menu+1
because you probably want to NULL
terminate your menu
.
Now you could fill it, e.g.
menu[0] = "Some string";
or better yet, use strdup(3).
You should have a convention (and document it) about when and which pointers are into the heap -i.e; malloc
-ed or calloc
-ed and who should free
them.
You should later free(3) your pointers to avoid memory leaks. You can only free
a pointer obtained by malloc
or calloc
or strdup
(which calls malloc
) etc...
On Linux, you should learn how to use valgrind. Perhaps using Boehm Garbage Collector could help you. Certainly, understand what garbage collectors are and learn a lot more about C memory management.
Actually, you could use flexible array members and have your menu
be a pointer to
struct menu_st {
unsigned nb_entries;
char* entry_array[]; // nb_entries elements in the array
};
Read about the C memory model.
Don't forget to compile with all warnings and debug info (e.g. gcc -Wall -g
) and learn how to use the debugger (e.g. gdb
). Be very scared of undefined behavior.