双选择排序(带指针)崩溃程序

时间:2015-08-27 20:46:23

标签: c++ sorting pointers selection

我刚刚开始编程,我仍然无法掌握指针。我正在尝试使用降低的测试分数进行选择排序,其中名称“附加”到测试分数。当我使用仅有分数的选择排序时,它完美地工作,但是当我基本上为与其各自的测试分数一起的名称编写相同的代码时,程序崩溃。这是功能:

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;
}

1 个答案:

答案 0 :(得分:0)

maxValuetempName不应该是指针。实际上,你只是通过纯粹的机会得到这个工作,因为解除引用的单元化指针构成了#34;未定义的行为。&#34;试试这个:

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;
}