I'd appreciate some help from anyone who can give it. I'm trying to set up a menu hierarchy with arrays of pointers to the struct. Right now it seems to be working partially, but I'm getting some weird results from the function.
3-4 of my 7 menus print out in correct fashion up until where they start to overlap.
I tested initializing several menus declared similarly to searchNameMenu below and testing the value of the memory addMenu has after the realloc and it tends to (seemingly) randomly be assigned a memory block from a previous array initialization. Why is this? I've already found out that I can't use sizeof on dynamically allocated arrays... am I using realloc on the array incorrectly?
Code:
typedef struct MenuStruct
{
char question[100];
void (*menuCommand) ();
struct menuStruct *nextMenu;
}menuStruct; //end menuStruct
typedef menuStruct *menuStructPtr;
menuStructPtr searchNameMenu[0];
void initSearchNameMenu()
{
int i = 0;
addMenuItem(searchNameMenu, "Search names by name.", NULL, &i);
addMenuItem(searchNameMenu, "Search names by length.", NULL, &i);
addMenuItem(searchNameMenu, "Search names by percentage.", NULL, &i);
addMenuItem(searchNameMenu, "Return to Previous Menu.", NULL, &i);
addMenuItem(searchNameMenu, "Return to Main Menu.", NULL, &i);
} //end function initSearchNameDBMenu
Function in question:
Code:
void addMenuItem(menuStructPtr addMenu[], char question[], menuStructPtr nextMenu[], int *i)
{
menuStructPtr newOption;
newOption = (menuStructPtr)malloc(sizeof(menuStruct));
strncpy(newOption->question, question, 100);
//newOption->nextMenu = nextMenu; this is used in my larger program
addMenu = (menuStructPtr*)realloc(addMenu, ((*i+1) * sizeof(newOption)));
if(addMenu == NULL)
printf("Oh noes, not enough mem");
//printf("%d\n", addMenu); this is what I used to test the memory being assigned
addMenu[*i] = newOption;
(*i)++;
} //end function addMenuItem
I tried to cut the code down as much as possible, I think this should be enough; as far as I know the error is in this function. If you would need to see code more to help, I can definitely provide it.