我在動態地將內存分配給指向結構的指針內的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中的兩個項目填充學生結構的字段。
指針數組中的指針指向內存中的隨機位置,並且您試圖使用這些隨機地址。這當然可以解釋爲什麼程序崩潰。實際上有很多方法可以使這個程序崩潰,所有的步驟都必須謹慎行事以避免這種情況。
但我不知道如何解決這個問題或從哪裏開始。