2015-05-22 50 views
0

我正在做一個編程主題的項目。他們要求將項目保存在鏈接列表中。在這裏,你有我的結構:鏈接列表與字符串

typedef struct dados { 

    int ID; 

    string title; 

    char institution[150]; 

    char investigator[150]; 

    string keywords[5]; 

    float money; 

    struct dados *next; //pointer to next nodule 

}No; 

這是該項目的第二階段,第一個是使用結構的簡單數組,但這個階段他們想要的相同,但有一個鏈表。

我有一個函數,我用它來在結構中插入數據。該函數要求輸入,並將數據保存在結構中。

插入功能:

No * insertBegin(No * head){ 

    No * newNode; 

    newNode= (No *)malloc(sizeof(No)); 

    cout << endl << "Qual e o titulo do projeto?" << endl << endl; 

    getline(cin, newNode->titulo) 

    //More data like this, on the end: 

    newNode->next= head; 
} 

要保存一個字符串,在第一階段的頭銜,我就是用這個:

getline(cin, no.title); 

我要爲第二階段做同樣的,我做:

getline(cin, no->title); 

但它給這個錯誤:

Unhandled exception at 0x00E14E96 in Aplicacao.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD. 

我不知道該怎麼做。你能幫我嗎?

非常感謝。

+0

'0xCDCDCDCD' =未初始化的堆內存。 – drescherjm

+0

你能更具體嗎?我是C/C++的新手。順便謝謝回答我。 – user3199227

+1

分享您的代碼插入 – Steephen

回答

1

正如其他人指出的,你不能使用malloc來創建「No」結構的實例,因爲malloc不會調用字符串的構造函數。所以函數變爲:

No * insertBegin(No * head){ 
    No * newNode; 

    //newNode= (No *)malloc(sizeof(No)); 
    newNode = new No(); 

    cout << endl << "Qual e o titulo do projeto?" << endl << endl; 

    getline(cin, newNode->titulo) 

    //More data like this, on the end: 

    newNode->next= head; 
} 

請注意,您不應該在對象上釋放()。相反,請使用delete關鍵字。