Ok, so I'm new to this posting for help on a forum deal. I've searched and searched, but can't seem to find why I'm running into this issue.
I'm working on an IntegerSet class for school, that uses a dynamic array. Per the directions for the assignment "A set is represented internally as a fixed array of ones and zeros or true and false. Array element a[ i ] is 1 or true if integer i is in the set. Array element a[ j ] is 0 or false if integer j is not in the set."
Here is my code:
Header:
// IntegerSetEC.h -- IntegerSet class specification file
#ifndef INTEGERSETEC_H
#define INTEGERSETEC_H
using namespace std;
const int MIN_SIZE = 128;
const int MAX_SIZE = 10000;
while (inputValue != -1 && j <= MAX_SIZE)
{
in >> inputValue;
if (inputValue < MAX_SIZE && inputValue >= 0)
{
if (inputValue >= s.arraySize)
{
int *tempPtr = nullptr;
tempPtr = new int[inputValue + 1];
for (int i = 0; i < inputValue + 1; i++)
{
tempPtr[i] = 0;
if (s.aPtr[i] == 1)
tempPtr[i] = 1;
}
delete [] s.aPtr;
s.aPtr = 0;
s.arraySize = inputValue + 1;
s.aPtr = new int[s.arraySize];
for (int i = 0; i < inputValue + 1; i++)
{
s.aPtr[i] = 0;
if (tempPtr[i] == 1)
s.aPtr[i] = 1;
}
delete [] tempPtr;
tempPtr = 0;
}
s.aPtr[inputValue] = 1;
}
j++;
}
return in;
}
ostream &operator<<(ostream &out, const IntegerSet &s)
{
int tally = 0;
out << "{";
for (int i = 0; i <= s.arraySize; i++)
{
if (s.aPtr[i] == 1)
{
if (tally == 0)
{
out << i;
tally++;
}
else
{
out << ", " << i;
tally++;
}
}
}
out << "}";
return out;
}
IntegerSet & IntegerSet::operator=(const IntegerSet &s)
{
if (arraySize > 0)
delete [] aPtr;
arraySize = s.arraySize;
aPtr = new int[arraySize];
for (int i = 0; i < arraySize; i++)
aPtr[i] = s.aPtr[i];
return *this;
}
Note: I'm overloading some operators (=, <<, >>, etc)
The issue I am having when I input (>>) data,
example: IntegerSet s;
cin >> s;
with my driver program works just fine for elements that are less than the initial array size (128). However, when I try to input values 138 or higher into the set, my program will output my those values plus others.
For example when I enter in the values: 138 -1
I believe the set should display {138}
BUT the dang thing keeps throwing in a 137 to make it {137, 138}
so frustrating! This is when I'm starting the program without debugging.
I got this feeling there's a memory leak somewhere haunting my code, but when I try and start the program with debugging this time and step through the loops and coding, the program will run exactly as I intend it to.
I know many of these forums frown upon people scheming for others to do their work, but if you could just point me in the right direction (ie there is/isnt a memory leak, something is up with my compiler, ???) I would greatly appreciate it.
Thanks Gamer2015, such an obvious answer, yet for whatever reason I was stuck in a box. I fixed the s.aPtr to point to where temp pointed to and everything finaaaallllly works!