views:

49

answers:

3
#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.

+2  A: 

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

Jim Ferrans
+1  A: 

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).

zdav
+1  A: 

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.

Christopher Monsanto