I'm trying to create a single 5 in the fifth instance of an array of twenty zeros. I did get the 5 where I wanted, but doing this has cause four additional zeros to follow raising the array count to 24. What is causing this to happen? I've tried everything, and changing it gives me junk values.
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
class PartFilledArray
{
public:
PartFilledArray(); //create instance
PartFilledArray(int array_size); //declares the sizes of arrays being added
//Overloading Assignment Operator
PartFilledArray operator = (const PartFilledArray& other)
{
if(this == &other) return *this; // handling of self assignment
delete[] a; // freeing previously used memory
double a[20];
int _size = number_used; memcpy(a, other.a, sizeof(int) * _size);
return *this;
}
void add_value(double new_entry);
void print_array();
//copy constructor
PartFilledArray::PartFilledArray( const PartFilledArray& other )
{
max_number = other.max_number;
number_used = other.number_used;
}
//deconstructor
~PartFilledArray()
{
//delete [] a;
}
protected:
double a[20]; //declares first array
int max_number;
int number_used;
};
#endif
//Precondition: an array of 20 elements must all equal 0.
//Postcondition: This fifth element in the array will take the value of 5.
int main ()
{
PartFilledArray instance(20);
instance.print_array();
int new_entry = 5; //declares at the fifth element
int array_size = 20;
instance.add_value(new_entry);
instance.print_array();
system ("pause");
return 0;
}
PartFilledArray::PartFilledArray(int array_size) : max_number(array_size), number_used(0)
{
{
for (int i = 0; i < array_size; i++)
{
a[i] = 0; // adds element in array
}
}
}
void PartFilledArray::add_value(double new_entry)
{
a[number_used] = new_entry;
number_used = number_used + 1;
}
void PartFilledArray::print_array()
{
for (int i = 0; i < 20; i++)
{
cout << a[i] << endl; //prints the array of elements
}
}