ncurses、menu.h 和 current_item() 的问题

Issues with ncurses, menu.h, and current_item()

我在使用 ncurses 中的菜单时遇到问题。我正在尝试设置一个菜单,让用户 select 一个选项,并根据他们的 selection 设置一个名为 num_players 的整数。 我使用 boost::lexical_castitem_name(current_item(my_menu)) 执行此操作,但每次我调用 current_item(my_menu) 时,我都会得到 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*;

为单个 ITEM* 分配足够的 space 并将指向 space 的指针分配给 my_items。随后尝试为 i 的任何值而不是 0 写入 my_items[i] 将覆盖随机内存,这至少可以说是未定义的行为。无论您的代码可能有什么其他问题,您都需要在继续之前解决它。

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

my_items = new ITEM*[num_choices + 1];

(真的,你应该把 my_items[6] = NULL; 中的 6 换成 num_choices;否则,你有一个 bug 等着咬你。)

完成后不要忘记使用 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()));

最后,在让 std::vector 析构之前,您仍然必须在每个 ITEM* 上调用 free_item

for (auto& item : my_items) free_item(item);