2016-09-19 36 views
1

我定義了一個結構並想初始化該結構的數組。該程序執行並寫入值到控制檯,但然後崩潰,我不知道爲什麼,因爲它不給我任何錯誤信息。我相信我的錯誤是當我嘗試將結構賦值給程序時,程序正常工作,但我無法弄清楚我做錯了什麼。我希望有人能幫助我。嘗試將結構指針指向某個結構時程序崩潰

struct Item{ 
    char *key; 
    char *val; 
}; 


int main() { 
    char k[] = "key"; 
    char v[] = "value"; 

    struct Item **dict = new struct Item*[3]; 
    dict[0]->key = k; 
    dict[0]->val = v; 

    cout << dict[0]->key << " "<< dict[0]->val << "\n"; 
    delete[] dict; 
} 

回答

4

通過這樣做:

struct Item **dict = new struct Item*[3]; 

您創建指針數組的指針struct Item注意:在C++中,您不需要struct資格來聲明struct對象。

創建的指針還沒有引用任何有效的對象,因此取消引用它們會產生未定義的行爲。那麼,在您初始分配後,您可能想要遍歷每個指針數組並創建該元素。例如:

for(int i = 0; i < 3; i++){ 
    dict[i] = new Item[4]; //as an array, or 
    //dict[i] - new Item(); 
} 

保存自己所有的頭痛和使用std::vector,並且還使用std::string太而非char*


今天的雷區,在C++中,這是你想要做什麼:

struct Item{ 
    std::string key; 
    std::string val; 
}; 


int main() { 
    std::string k = "key"; 
    std::string v = "value"; 

    //auto dict = std::make_unique<Item[]>(3);  
    std::vector<Item> dict(3); 
    dict[0].key = k; 
    dict[0].val = v; 

    std::cout << dict[0].key << " "<< dict[0].val << "\n"; 
} 

同樣地,如果你的目的是鍵/值的地圖,你可以簡單地使用std::map由MM的建議,或std::unordered_map

+0

偉大的答案謝謝你完美的作品 – moonboon

+0

使用'std :: map'可能是一個更好的「現代C++」等價物 –