我承认我完全被难过了。这是你只能从c ++这样的语言中获得的错误之一。
我有一个结构数组,我正在修改成员数据。真正的正常任务。我有一个函数可以获取一些成员数据,然后该函数调用另一个函数来获取其他成员数据。当我使用Visual Studio调试器逐步执行时,所有的分配似乎都很顺利。我在底部的调试窗口中观察变量的变化。但是一旦第二个函数返回到调用函数,数据就会消失。它可以追溯到未分配的乱码。任何想法?
编辑:不要将此问题标记为值/参考讨论的副本。它应该被删除以获得唯一性,或者单独留下。这个网站上的答案太多被标记为重复,因为其他地方的答案可能会回答问题,即使问题不同。如果问题不同,它们应该是分开的。
这两个功能:
void GetTestData(Student* students, int numStudents, int numTests)
{
// Loop through the i students and all j tests
for (int i = 0; i < numStudents; ++i)
{
// get test scores
for (int j = 0; j < numTests; ++j)
{
cout << "What was " + students[i].Name + "'s score for test #" + to_string(j + 1) + "? ";
cin >> students[i].Tests[j];
}
CalcGrades(students[i], numTests);
}
}
void CalcGrades(Student student, int numTests)
{
double sum = 0;
// add up all the scores
for (int i = 0; i < numTests; ++i)
{
sum += student.Tests[i];
}
// calculate the average and store it in the members
student.Avg = sum / numTests;
// grade assignment tree
if (student.Avg >= 91)
{
student.Grade = 'A';
}
else if (student.Avg >= 81)
{
student.Grade = 'B';
}
else if (student.Avg >= 71)
{
student.Grade = 'C';
}
else if (student.Avg >= 61)
{
student.Grade = 'D';
}
else
{
student.Grade = 'F';
}
}
答案 0 :(得分:2)
@James Root所说的问题是通过引用传递vs传递值。对Student进行更改后,将其传递回数组。
Student* GetTestData(Student* students, int numStudents, int numTests)
{
// Loop through the i students and all j tests
for (int i = 0; i < numStudents; ++i)
{
// get test scores
for (int j = 0; j < numTests; ++j)
{
cout << "What was " + students[i].Name + "'s score for test #" + to_string(j + 1) + "? ";
cin >> students[i].Tests[j];
}
students[i] = CalcGrades(students[i], numTests); //after the value was changed, store it in the array
}
return students;
}
Student CalcGrades(Student student, int numTests)
{
double sum = 0;
// add up all the scores
for (int i = 0; i < numTests; ++i)
{
sum += student.Tests[i];
}
// calculate the average and store it in the members
student.Avg = sum / numTests;
// grade assignment tree
if (student.Avg >= 91)
{
student.Grade = 'A';
}
else if (student.Avg >= 81)
{
student.Grade = 'B';
}
else if (student.Avg >= 71)
{
student.Grade = 'C';
}
else if (student.Avg >= 61)
{
student.Grade = 'D';
}
else
{
student.Grade = 'F';
}
return student;
}
答案 1 :(得分:1)
最好的解决方案是在GetTestData中将调用移到循环外的CalcGrades,并将其重写为所有学生的完整循环,就像其他函数一样。这避免了指针的缺点。