【问题标题】:Dual Selection sort (with pointers) crashes program双重选择排序(带指针)使程序崩溃
【发布时间】:2015-08-28 04:55:03
【问题描述】:

我刚刚开始重新编程,但我仍然无法掌握指针的窍门。我正在尝试使用降序的测试分数进行选择排序,名称“附加”到测试分数。当我只使用分数的选择排序时,它工作得很好,但是当我基本上为与它们各自的测试分数一起出现的名称编写相同的代码时,程序就会崩溃。函数如下:

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

【问题讨论】:

    标签: c++ sorting pointers selection


    【解决方案1】:

    maxValuetempName 不应该是指针。真的,你得到这个工作纯粹是偶然的,因为取消引用统一化的指针是构成“未定义的行为”。试试这个:

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

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2015-04-10
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多