I am trying to insert into a dynamic array. Everything seems to be working except for the first insertion.
Here is my insert function:
void account::insert(value_type entry) {
if (numberOfItems == 0) {
data = new value_type[numberOfItems + 1];
}
data[numberOfItems] = entry;
numberOfItems++;
value_type* temp = new value_type[numberOfItems + 1];
for (size_t i = 0; i < numberOfItems; i++) {
temp[i] = data[i];
}
delete[] data;
data = temp;
}
This is where I call my insert:
void account::deposit(double deposit) {
balance += deposit;
insert(balance);
}
here are my tests:
account savings(3.00);
savings.deposit(1.00);
cout << savings << endl;
savings.advanceDay(7);
cout << savings << endl;
savings.deposit(450.55);
cout << savings << endl;
savings.advanceDay(23);
cout << savings << endl;
savings.advanceDay(65);
cout << savings << endl;
//Deposit more
savings.deposit(1000);
cout << savings << endl;
savings.advanceDay(65);
cout << savings << endl;
here is the output I get:
Account Tester
day: 1, balance: $-6277438562204192487878988888393020692503707483087375482269988814848.00
day: 8, balance: $-6277438562204192487878988888393020692503707483087375482269988814848.00
day: 8, balance: $451.55
day: 31, balance: $451.55
day: 96, balance: $451.55
day: 96, balance: $451.55
day: 161, balance: $1451.55
day: 161, balance: $1451.55
day: 161, balance: $1451.55
day: 161, balance: $1451.55
day: 161, balance: $1451.55
day: 191, balance: $11401.55
day: 221, balance: $11401.55
I am confused why the fisrt balance is a garbage address value(or at least thats what I think it is)and not $1 but all the other depostits are correct.
This function
void account::insert(value_type entry) {
if (numberOfItems == 0) {
data = new value_type[numberOfItems + 1];
}
data[numberOfItems] = entry;
numberOfItems++;
value_type* temp = new value_type[numberOfItems + 1];
for (size_t i = 0; i < numberOfItems; i++) {
temp[i] = data[i];
}
delete[] data;
data = temp;
}
Has a bug. When numberOfItems us equal to 0 you are allocating an array with one element
if (numberOfItems == 0) {
data = new value_type[numberOfItems + 1];
}
data[numberOfItems] = entry;
numberOfItems++;
Then you are increasing numberOfItems. And then again you are allocating an array but now with 2 elements.
value_type* temp = new value_type[numberOfItems + 1];
and as a result the array has an element with an indeterminate value.
There is no sense to separate the function into two code snippets that allocate memory.
Initially the data member data shall be equal to nullptr. The function can look like
void account::insert( const value_type &entry )
{
value_type* temp = new value_type[numberOfItems + 1];
for ( size_t i = 0; i < numberOfItems; i++ )
{
temp[i] = data[i];
}
temp[numberOfItems++] = entry;
delete [] data;
data = temp
}