c++ dynamic array Floating Point exception -
for homework had design arraylist in c++ using 1d arrays , pointers make array dynamic. have done ample testing , functions work correctly, when use main teacher has provided me floating point error. point of homework create class work teachers main without changing code in main
here main:
#include "arraylist.h" #include <iostream> using namespace std; int main(int argc,char *argv[]) { arraylist arr; (int i=1;i<=50;i++) { arr.push_back(i); } cout << "should contain numbers 1..50, "; cout << arr.tostring() << endl; (int i=arr.size()-1;i>=1;i--) { arr.erase(arr[i]); } cout << "should contain 1, "; cout << arr.tostring() << endl; arr.erase(arr[0]); (int i=1;i<=50;i++) { if (i<=2) arr.push_back(i); else { int j=1; while ((j<arr.size()) && (i%arr[j]!=0)) j++; if (j==arr.size()) { arr.push_back(i); } } } cout << "prime numbers between 1 , 50 are: " << arr.tostring() << endl; }
here cpp:
#include<iostream> #include<string> #include<sstream> #include "arraylist.h" using namespace std; void arraylist:: intialarr(int arr[]) { for(int = 0; < length; i++) { arr[i] = 0; } } string arraylist:: tostring() { std::ostringstream ss; for(int = 0; < capacity; i++) { if(arr[i]>0 || arr[i] <0) { ss << arr[i] << " "; } } return ss.str(); } arraylist::arraylist() { length = 1; capacity=0; arr = new int[length]; intialarr(arr); } int& arraylist:: operator[] (unsigned int i) { return arr[i]; } void arraylist:: push_back(int m) { if(capacity>=length) { int oldlength = length; length = length*2; int* curarr = new int[length]; intialarr(curarr); (int = 0; < oldlength; i++) { curarr[i] = arr[i]; } delete [] arr; arr = curarr; } arr[capacity] = m; capacity++; } void arraylist:: erase(int m) { if(capacity == length/2) { length = length/2; int* curarr = new int[length]; intialarr(curarr); (int = 0; i<capacity; i++) { curarr[i] = arr[i]; } delete [] arr; arr = curarr; } for(int = 0; < capacity; i++) { if(arr[i]==m) { for(int j = i; j<length; j++) { arr[j] = arr[j+1]; } capacity--; break; } } cout << "length = " << length << " capacity = " << capacity << " capacity/length = " << capacity*2 << endl; }
from have read online floating point exceptions thrown when try divide 0 or infinate value arises dont understand how getting either of these issues arise.
my code through main number 1-50 added , deleted error once go setting array hold prime numbers (after arr.erase(arr[0]) in main)
i set couple of tags in main find number going while ((j<arr.size()) && (i%arr[j]!=0))
and find numbers before crash
j = 1 , arr[j] = 2 = 5 , arr.size() = 4