C++ 双重选择排序(带指针)程序崩溃
我刚刚重新开始编程,但我仍然无法掌握指针的窍门。我正在尝试对测试分数进行降序排序,并将名字附加到测试分数上。当我只对分数使用选择排序时,它工作得很好,但是当我基本上为与它们各自的测试分数对应的名称编写相同的代码时,程序崩溃了。下面是函数:C++ 双重选择排序(带指针)程序崩溃,c++,sorting,pointers,selection,C++,Sorting,Pointers,Selection,我刚刚重新开始编程,但我仍然无法掌握指针的窍门。我正在尝试对测试分数进行降序排序,并将名字附加到测试分数上。当我只对分数使用选择排序时,它工作得很好,但是当我基本上为与它们各自的测试分数对应的名称编写相同的代码时,程序崩溃了。下面是函数: void sortScores (double scores[], int num, string names[]) { int startScan, maxIndex; double* maxValue; string* tempName;
void sortScores (double scores[], int num, string names[])
{
int startScan, maxIndex;
double* maxValue;
string* tempName;
for (startScan = 0; startScan < (num - 1); startScan++)
{
maxIndex = startScan;
*maxValue = scores[startScan];
*tempName = names[startScan];
for (int index = (startScan + 1); index < num; index++)
{
if (scores[index] > *maxValue)
{
*maxValue = scores[index];
*tempName = names[index];
maxIndex = index;
}
}
scores[maxIndex] = scores[startScan];
names[maxIndex] = names[startScan];
scores[startScan] = *maxValue;
names[startScan] = *tempName;
}
// for (int i = 0; i < num; i++)
// cout << scores[i] << " " << names[i] << endl;
}
maxValue和tempName不应是指针。事实上,这完全是偶然的,因为去引用统一化的指针是未定义的行为。试试这个:
void sortScores (double scores[], int num, string names[])
{
int startScan, maxIndex;
double maxValue;
string tempName;
for (startScan = 0; startScan < (num - 1); startScan++)
{
maxIndex = startScan;
maxValue = scores[startScan];
tempName = names[startScan];
for (int index = (startScan + 1); index < num; index++)
{
if (scores[index] > maxValue)
{
maxValue = scores[index];
tempName = names[index];
maxIndex = index;
}
}
scores[maxIndex] = scores[startScan];
names[maxIndex] = names[startScan];
scores[startScan] = maxValue;
names[startScan] = tempName;
}
// for (int i = 0; i < num; i++)
// cout << scores[i] << " " << names[i] << endl;
}