I know this is a C++ forum, but I figured there will (hopefully) be quite a few C people here as well.
My problem is this: I have to use plain C for my entire program, which is a text-based game. Naturally, I have to use a lot of strings.
What I want to do is pass and array of strings (which would be a char[][]) and loop through the array, printing the strings.
Here's my function:
1 2 3 4 5 6 7
int menu(char choices[][]) {
int i;
for(i = 0; i < sizeof(choices); i++) {
printf("%d: %s", i, choices[i]);
}
return 0;
}
Well, that doesn't work. I get an error saying "invalid use of array with unspecified bounds."
As this function is to be kind of an all purpose function for as many amount of strings and strings of all lengths, I can't really place a length in the array declaration.
Is there a way to get the above function to work without limiting capabilities?
#include <stdio.h>
// Every element of this array is a char*
constchar* main_menu[] =
{
"Look"
, "Go North"
, "Go South"
, "Go East"
, "Go West"
, 0 // zero terminator marks end of array
};
// The final char* is a zero so you can find the end
// when you are looping.
int menu(constchar* choices[]) // array of char*
{
int i = 0;
// Loop until you find a zero value char*
// which you put in your array to mark the end
for(constchar** c = choices; *c; ++c)
{
printf("%d: %s\n", ++i, *c);
}
// get choices using scanf() etc...
return i;
}
int main()
{
int choice = menu(main_menu);
}
1: Look
2: Go North
3: Go South
4: Go East
5: Go West