2013-10-16 40 views
-2

我在動態地將內存分配給指向結構的指針內的char數組時遇到了問題。 這是必須使用這個結構輪廓家庭作業:C++ dynamic stuct指向字符數組的指針

struct Student 
{ 
char *namePtr; 
unsigned int score; 
}; 

這是一種具有雖然

/*************************** 
* takes value from temporary value and puts into dynamic allocated Student array 
***************************/ 
bool updateStructPtr(Student **info, unsigned int index, char *name, unsigned int score) 
{ 
try 
{ 
    info[index]->namePtr = new char [strlen(name)+1]; 
    if(DEBUG) cout << "size for dynamic char: " << strlen(name)+1 << endl << endl; 
    //copy char array into new array 
    strcpy(info[index]->namePtr, name); 
    info[index]->score = score; 
} 
catch (bad_alloc & param) 
{ 
    info[index]->namePtr = NULL; 
    return false; 
} 
return true; 
} 

我的教授說,麻煩的部分IM: 你的代碼看一眼表明您似乎沒有爲我提供的算法的步驟3-2的第一句中指定的Student結構動態分配內存。

3-2。爲學生結構動態分配內存。將此Student結構的地址放置在結構指針數組中。您還需要動態分配足夠的內存來存儲名稱。不要存儲引號字符。使用步驟3-1中的兩個項目填充學生結構的字段。

指針數組中的指針指向內存中的隨機位置,並且您試圖使用這些隨機地址。這當然可以解釋爲什麼程序崩潰。實際上有很多方法可以使這個程序崩潰,所有的步驟都必須謹慎行事以避免這種情況。

但我不知道如何解決這個問題或從哪裏開始。

回答

0

SO並非真正用於幫助您的功課。

這就是說,你的老師的指示是相當詳盡和正確的。您必須在某個點或另一個位置使用new Studentnew Student[]以實際更新傳遞給您的Student ** info,以便添加您應該添加的新Student結構。

0

我猜Student實例在函數調用之前未分配。您將不得不通過new Student分配Student的新實例,並將其存儲在infoindex

info[index] = new Student;