我正在构建一个动态堆栈,它需要一个带有指向数组的指针的结构。
class studentstack
{
private:
struct StackNode
{
int ID;
string Name;
string Address;
StackNode * next; // pointer to the next node
double * scores; // pointer to the arry of scores
};
当我在我的主文件中尝试用双打填充数组然后将其传递给函数时,当我什么都不做时似乎正确传递。这样做的正确方法是什么?
int main()
{
studentstack s;
string name;
int id;
string address;
double score;
for(int x =0; x<20; x++)
{
cout << "\nNew Student Name: ";
cin >> name;
cout << "\nID: ";
cin >> id;
cout << "\nAddress: ";
cin >> address;
double scoresArr[10];
for(int z=0; z<10; z++)
{
cout << "\nStudent Score " << z+1 << ": ";
cin >> score;
scoresArr[z] = score;
}
s.push(name, id, address, scoresArr);
推:
void studentstack::push(string name, int id, string address, double scoresArr)
{
StackNode *newStudent; // To point to the new Student
newStudent = new StackNode;
newStudent-> ID = id;
newStudent-> Name = name;
newStudent-> Address = address;
newStudent-> scores = scoresArr;
// If there are no nodes in the stack
if (isEmpty())
{
top = newStudent;
newStudent->next= NULL;
}
else // or add before top
{
newStudent->next = top;
top = newStudent;
}
}
答案 0 :(得分:0)
技术问题出现在你尚未展示的代码中(正如我写的那样),即push
代码。
然而,无论您的push
如何搞砸事情,都有一个简单的解决方案。
即,使用std::vector
而不是动态分配的原始数组。
或者,只需在每个节点中使用固定大小的原始数组。
就此而言,std::list
会比DIY链接列表更好,但大概这个练习的重点是要熟悉链表结构。在每个节点中使用std::vector
数组,不会干扰该目标。但请记住,在现代C ++中,创建链表本身很少是一个很好的解决方案,无论问题是什么 - 相反,使用标准库容器类和/或第三方库中的容器类。