C++ ncurses、menu.h和当前_项()的问题

C++ ncurses、menu.h和当前_项()的问题,c++,c,menu,ncurses,curses,C++,C,Menu,Ncurses,Curses,我在课程菜单上遇到了问题。我试图设置一个菜单,让用户选择一个选项,并根据他们的选择设置一个名为num_players的int。 我使用boost::lexical\u cast和item\u namecurrent\u itemmy\u菜单执行此操作,但每次调用current\u itemmy\u菜单时,我都会得到NULL。 下面是有问题的代码示例: char *choices[] = {"1", "2", "3", "4", "5", "6"}; //create the dynami

我在课程菜单上遇到了问题。我试图设置一个菜单,让用户选择一个选项,并根据他们的选择设置一个名为num_players的int。 我使用boost::lexical\u cast和item\u namecurrent\u itemmy\u菜单执行此操作,但每次调用current\u itemmy\u菜单时,我都会得到NULL。 下面是有问题的代码示例:

char *choices[] = {"1", "2", "3", "4", "5", "6"};
    //create the dynamic array for the items and their description
    ITEM** my_items;
    MENU *my_menu;
    int num_choices = 6;
    my_items = new ITEM*;
    for (int x = 0; x < num_choices; x++)
    {
       my_items[x] = new_item(choices[x], choices[x]); 
    }
    my_items[6] = (ITEM*)NULL;
    my_menu = new_menu((ITEM**)my_items);
    set_menu_mark(my_menu, " * ");
    set_current_item(my_menu, my_items[0]);
    post_menu(my_menu);
    wrefresh(scr);

    int c;
    while((c = wgetch(scr)) != '\n')
    {   switch(c)
        {   case KEY_DOWN:
                menu_driver(my_menu, REQ_DOWN_ITEM);
                break;
            case KEY_UP:
                menu_driver(my_menu, REQ_UP_ITEM);
                break;
        }
    }
    //right here, calling current_item just gives me null
    //am I supposed to unpost the menu first?
    //what am I doing wrong? this is frustrating
    ITEM* cur = current_item(my_menu);
    setNumPlayers((char*) item_name(cur));
    unpost_menu(my_menu);
    free_item(my_items[0]);
    free_item(my_items[1]);
    free_item(my_items[2]);
    //etc etc
本声明:

my_items = new ITEM*;
为单个项目*分配足够的空间,并将指向该空间的指针分配给my_项目。随后,尝试为除0以外的任何i值写入my_items[i]将覆盖随机内存,这至少是一种未定义的行为。无论您的代码可能有什么其他问题,您都需要在继续之前解决这些问题

从代码中可以清楚地看出,您希望能够在数组中存储num_choices+1 ITEM*s,因此您需要分配一个至少具有该大小的数组

my_items = new ITEM*[num_choices + 1];
实际上,您应该替换my_items[6]=NULL中的6;有很多选择;否则,你会有一只虫子等着咬你

完成后,不要忘记使用delete[]而不是delete

但是既然你使用C++,你不妨好好利用它:

std::vector<ITEM*> my_items;
for (int x = 0; x < num_choices; x++) {
   my_items.emplace_back(new_item(choices[x], choices[x])); 
}
my_items.emplace_back(nullptr);
/* Unfortunately, new_menu requires a non-const ITEM**,
 * even though it should not modify the array. */
my_menu = new_menu(const_cast<ITEM**>(my_items.data()));

非常感谢你,我觉得自己很笨。
for (auto& item : my_items) free_item(item);