Hi all
Ok in class to do we had to do the following and I keep on running into the same problem:
/after I jump into a2->add(temp) i get an access violation.
Any help would be great
Ok in class to do we had to do the following and I keep on running into the same problem:
Code:
class Array
{
public:
Array(int size); //constructor - sets capacity to size
void print(); //prints the contents of the Array
void add(int value); //adds element to end of Array
~Array(); //destructor
private:
int length; //number of elements
int capacity; //size of internal array
int* list; //pointer to internal array
void doubleCapacity(); //doubles the capacity
};
int main()
{
srand(time(NULL));
Array* a2 = new Array(1);
//do the following:
//add 9 elements to a2
for(int index1 = 0 ; index1 < 10; index1++ )
{
//This is where I hit the problem it jumps from here into add
//then it runs into trouble
a2->add(5);
}
// print a2
a2->print();
// cleanup
delete a2;
system("pause");
return 0;
}
Array::Array(int size) : capacity(size), length(0)
{
int *list = new int[capacity];
}
void Array::print()
{
for(int i = 0; i < length; i++)
{
cout << list[i] << ", ";
}
cout << endl;
}
void Array::add(int value)
{
if(length < capacity)
{
list[length] = value;
length++;
}
else
{
doubleCapacity();
list[length] = value;
length++;
}
}
Array::~Array()
{
delete [] list;
list = NULL;
}
void Array::doubleCapacity()
{
int oldcapacity = capacity;
capacity *= 2;
int* temp= new int[capacity];
for(int index = 0; index < oldcapacity; index++)
{
temp[index] = list[index];
}
delete [] list;
list = temp;
}
Any help would be great
Comment