Question

#include <iostream>
using namespace std;

int main ()
{
 int size = 0;
 int* myArray = new int [size + 1];
 cout << "Enter the exponent of the first term: ";
 cin >> size;
 cout << endl;
 for (int i = size; i >= 0; --i)
 {
  cout << "Enter the coefficient of the term with exponent " 
   << i << ": ";
  cin >> myArray[i];
 }
 for (int i = size; i >= 0; --i)
 {
  cout << i << endl;
 }
 return 0;
}

Why am I getting an assertion error on input greater than 2? This is the precursor to a polynomial program where the subscript of the array is the power of each term and the element at array[subscript] is the coefficient.

Was it helpful?

Solution

Your array is allocated to be an int[1]. It needs to be allocated after you read in the size value.

OTHER TIPS

You are initializing your array when size = 0, giving an array size of 1 You get your assertion error when you go outside of the array bounds (1).

myArray always has size 0 + 1 = 1. i starts out at whatever the user inputted, and the first array access you make is myArray[i]. So, say the user inputs 5, your array has size 1 and you access myArray[5]. It will fail!

I would allocate the array AFTER you input size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top