-1

Getting this error from my code. I had looked at similar questions on here but wasn't able to see why mine wasn't working (most answers involved chars and people using " instead of ', which wasn't really helpful to me). Not sure what I'm missing here. Edit: To be a little more specific it's the ">" sign in my if statement that is giving me trouble. My code is below:

    int main()
{
int numGrades = 0;
double *scores = nullptr;
double total = 0;
cout << fixed << setprecision(1);

cout << "How many grades would you like to enter? ";
cin >> numGrades;
if (numGrades < 0)
{
    cout << "Error, please enter positive values only: ";
    cin >> numGrades;
}
scores = new double[numGrades];
for (int x = 0; x <= numGrades; x++)
{
    cout << "Please enter student " << (x + 1) << "'s score: ";
    cin >> scores[numGrades];
    if (scores < 0 && scores > 100)     //ERROR IS HERE
    {
        cout << "Please enter a value between 0 and 100: ";
        cin >> scores[numGrades];
    }
}
Nick5227
  • 21
  • 1
  • 5
  • Scores is a pointer, you've forgotten to dereference it – OMGtechy Nov 03 '16 at 02:04
  • Also, you're running off the end of the array, resulting in undefined behavior and corrupted memory, because your `for` loop iterates one too many. – Sam Varshavchik Nov 03 '16 at 02:05
  • Also, once you've done that what you've written doesn't make much sense. Did you mean loop through the array and find the min/max, then compare with 0/100? – OMGtechy Nov 03 '16 at 02:05
  • @OMGtechy Sorry, I'm new to this, I'm not sure what you mean D: – Nick5227 Nov 03 '16 at 02:07
  • @OMGtechy the if statement is supposed to just error trap and make sure that I don't input a value below 0 or above 100 – Nick5227 Nov 03 '16 at 02:07
  • That's not what it does. It compared the address of scores with 0 and 100 (hence the error message). Sounds like you need to brush up on your pointers and dynamically allocated arrays, good luck :) – OMGtechy Nov 03 '16 at 02:09

2 Answers2

1

cin >> scores[numGrades]; is assigning data outside of the allocated memory; anything after that is undefined behavior.

Did you mean cin >> scores[x];?

Aganju
  • 6,295
  • 1
  • 12
  • 23
0
if (scores < 0 && scores > 100)     //ERROR IS HERE
{
    cout << "Please enter a value between 0 and 100: ";
    cin >> scores[numGrades];
}

That's what you wrote. However a number cannot be smaller than 0 and larger than 100 so this is how you should fix it.

if (scores < 0 || scores > 100)
{
    cout << "Please enter a value between 0 and 100: ";
    cin >> scores[numGrades];
}