Brandon Tiqui
Brandon Tiqui

Reputation: 1439

Why am I getting an assertion error?

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

Upvotes: 0

Views: 244

Answers (3)

Christopher Monsanto
Christopher Monsanto

Reputation: 881

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.

Upvotes: 0

zdav
zdav

Reputation: 2748

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

Upvotes: 1

Jim Ferrans
Jim Ferrans

Reputation: 31012

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

Upvotes: 3

Related Questions