So I was experimenting with a few lines of code in C, and came across this problem. I have a structure with the following definition:
typedef struct menuScreen
{
char *lines[MENU_MAX_LINES];
}menuScreen;
With that, I have a 2D character array declared as:
static char array1[][MENU_MAX_CHAR_PER_LINE] = {
"Line 1",
"Line 2",
"Line 3",
"Line 4"
};
Then I have a function:
void buildMenu(menuScreen *menu, const char lines[][MENU_MAX_CHAR_PER_LINE])
{
int i = 0;
for(i = 0; i < MENU_MAX_LINES; i++)
{
menu->lines[i] = (char *) lines[i];
}
}
And finally a print function for the menu:
void printMenu(menuScreen *menu)
{
int i = 0;
for(i = 0; i < MENU_MAX_LINES; i++)
{
printf("%s\n", menu->lines[i]);
}
}
In main.c:
menuScreen selectMenu[2];
buildMenu(&selectMenu[0], array1);
printMenu(&selectMenu[0]);
Now everything works fine. Printing is fine as well. Then I decided to convert my character array as follows:
static char *array1[MENU_MAX_CHAR_PER_LINE] = {
"Line 1",
"Line 2",
"Line 3",
"Line 4"
};
and changed the function to:
void buildMenu(menuScreen *menu, const char **lines)
{
int i = 0;
for(i = 0; i < MENU_MAX_LINES; i++)
{
menu->lines[i] = (char *) lines[i];
}
}
And finally in main.c, I call the functions as:
menuScreen selectMenu[2];
buildMenu(&selectMenu[0], (const char**) array1);
printMenu(&selectMenu[0]);
And again, everything is great. Works as required.
Now, given all the above, I would like to know how to generalize the buildMenu() function so that I can pass both char[][] and char *[] in one function itself. Cant use function overloading as I am using C, and not C++. Maybe can be done with function pointers, but just want to know if it is possible by adjusting the argument to the function.