为什么这段代码导致程序停止工作?

时间:2015-10-24 22:22:31

标签: c++ arrays runtime-error

当你运行它时,带有错误注释的行会导致程序停止工作,至少对我而言。这是如此简单的代码,我有点困惑,为什么这会导致事情破裂?

#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
using namespace std;

static const int ARRAY_SIZE = 100;

bool runAgain ( ) {
    char runChar;

    cout << "\n\nRun again? (Y/N)";
    cin >> runChar;
    runChar = toupper(runChar);
    if(runChar != 'Y')
        return false;

    system("cls");
    return true;
}

int main ( ) {

   int nums[ARRAY_SIZE];
   int length;
   int num, highIndex, lowIndex;

   length = sizeof(nums)/sizeof(int);
   srand((unsigned)time(NULL)); //make numbers more random

   do {

      cout << "Array contains: \n";

      for(int i = 0; i < length; i++) {
         num = rand() % 1000 + 1;

         if(i == 0)
             highIndex, lowIndex = i;
         else if(num > nums[highIndex]) //@@ ERROR occurs on this line
             highIndex = i;
         else if(num < nums[lowIndex])
             lowIndex = i;

         nums[i] = num;

         cout << num << "\n";
      }

      cout << "\nHighest Value: " << nums[highIndex] << " at index " << highIndex;
      cout << "\nLowest Value: " << nums[lowIndex] << " at index " << lowIndex;

   }while(runAgain());

   return 0;
}

错误特别是windows说.cpp已经停止工作并且表面上结束了运行。从运行调试器开始,我知道它发生在第一次迭代之后的第一次迭代中,如果在for循环中。

编辑:啊,是的,问题是'highIndex,lowIndex = i'。谢谢你的帮助

1 个答案:

答案 0 :(得分:2)

问题是highIndex, lowIndex = i;

根据您的想法,这并不是highIndexlowIndex i的值。仅指定了lowIndexhighIndex仍然未初始化。因此,当您尝试使用highIndex取消引用数组时,程序会崩溃,因为值可能是任何值。

将您的代码行更改为:

highIndex = lowIndex = i;
相关问题