2015-09-04 31 views
0

我在ncurses中遇到菜單問題。我試圖建立一個菜單,讓用戶選擇一個選項,並根據他們的選擇設置一個名爲num_players的int。 我這樣做boost::lexical_castitem_name(current_item(my_menu))但我每次打電話current_item(my_menu)我只是得到NULL。 這裏是有問題的代碼示例:ncurses,menu.h和current_item()的問題

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 

回答

0

本聲明:

my_items = new ITEM*; 

單個ITEM*分配足夠的空間和分配指針指向的空間my_items。隨後嘗試寫入my_items[i]以獲得除0以外的任何值i將覆蓋隨機存儲器,這是 - 說至少 - 未定義的行爲。無論您的代碼可能存在哪些其他問題,您需要先解決該問題,然後再繼續。

從代碼中可以清楚地看到,您希望能夠在數組中存儲num_choices + 1ITEM* s,因此您需要分配一個至少具有該大小的數組。

my_items = new ITEM*[num_choices + 1]; 

(真的,你應該在my_items[6] = NULL;num_choices更換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())); 

最後,你還是讓std::vector自毀之前調用每個ITEM*free_item

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

非常感謝,我覺得很愚蠢。 – destrovel