I am trying to print out an array of integers. I am getting a seg fault when I try to print as below. If I uncomment the "In for loop" it will print everything except the last item of the array and it still has a seg fault. When I uncomment both of the comments (or just the "done with for loop") everything prints fine. Why does this happen and how do I fix it?
for( int i = 0; i < l.usedLength; i++ )
{
//cout << "**********In for loop" << endl;
cout << l.largeInt[ i ];
}
//cout << "**********done with for loop" << endl;
Here is the whole class:
#include "LargeInt.h"
#include <ctype.h>
LargeInt::LargeInt()
{
usedLength = 0;
totalLength = 50;
largeInt = new int[totalLength];
for( int i=0; i<totalLength; i++ )
{
largeInt[i] = 0;
}
}
LargeInt LargeInt::operator+(const LargeInt &l) const
{}
LargeInt LargeInt::operator-(const LargeInt &l) const
{}
LargeInt LargeInt::operator*(const LargeInt &l) const
{}
LargeInt LargeInt::operator/(const LargeInt &l) const
{}
bool LargeInt::operator==(const LargeInt &l) const
{}
ostream& operator<<(ostream &out, const LargeInt &l)
{
cout << "In output" << endl;
if( l.usedLength == 0 )
{
cout << 0;
}
else
{
cout << "In else... NON 0" << endl;
for( int i = 0; i < l.usedLength; i++ )
{
cout << "In for loop" << endl;
cout << l.largeInt[ i ];
}
//cout << "done with for loop" << endl;
}
//cout << "after the if.... all done with output" << endl;
}
istream& operator>>(istream &in, LargeInt &l)
{
char x;
while (std::cin.get(x) && x >= '0' && x <= '9')
{
l.largeInt[ l.usedLength ] = x-48;
l.usedLength++;
//need to check array length and make bigger if needed
}
}
Main:
#include <stdlib.h>
#include <iostream>
#include "LargeInt.h"
int main(int argc, char** argv) {
cout << "\nJosh Curren's Assignment #5 - Large Integer\n" << endl;
LargeInt lint;
cout << "Enter a large int: ";
cin >> lint;
cout << "\nYou entered: " << endl;
cout << lint << endl;
cout << endl;
return (EXIT_SUCCESS);
}