我在使用 ncurses 中的菜单时遇到问题。我正在尝试设置一个菜单,让用户选择一个选项,并根据他们的选择设置一个名为 num_players 的 int 。
我用 boost::lexical_cast
和 item_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*
分配足够的空间,并将指向该空间的指针分配给my_items
。随后尝试写入除 0 之外的任何 i
值的 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()));
最后,您仍然需要在每个 ITEM*
上调用 free_item
,然后才能让 std::vector
析构:
for (auto& item : my_items) free_item(item);
关于c++ - ncurses、menu.h 和 current_item() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32400501/