I wrote my first ever C++ template code on expandable array and I am getting a segmentation fault! After an hour of debugging I have realized that I need help. Something is wrong with the constructor or the destructor I think but not sure.
The code is on pastie ready to be compiled. http://pastie.org/1150617
/* Expandable array in C++ */
#include <iostream>
using namespace std;
template <class T>
class EArray{
private:
T* arr;
int size;
public:
EArray(int l);
~EArray();
void setElement(int i, const T& newval);
void eraseElement(int i);
void addElement(int i, const T& newval);
void push(const T& newval);
void display();
};
template <class T>
EArray<T>::EArray(int l){
size = l;
}
template <class T>
EArray<T>::~EArray(){
delete [] arr;
arr = NULL;
}
template <class T>
void EArray<T>::setElement(int i, const T& newval){
if(i < size && i >= 0){
arr[i] = newval;
}
}
template <class T>
void EArray<T>::eraseElement(int index){
size -= 1;
T* newarr = new T[size];
for (int i = 0; i < size+1; i++){
if (i < index){
newarr[i] = arr[i];
}
else if(i > index){
newarr[i-1] = arr[i];
}
}
delete [] arr;
arr = newarr;
}
template <class T>
void EArray<T>::addElement(int index, const T& newval){
size += 1;
T* newarr = new T[size];
for(int i = 0; i < size; i++){
if(i<index){
newarr[i] = arr[i];
}
else if (i == index){
newarr[i] = newval;
}
else{
newarr[i] = arr[i-1];
}
}
delete [] arr;
arr = newarr;
}
template <class T>
void EArray<T>::push(const T& newval){
size += 1;
T * newarr = new T[size];
for (int i = 0; i < size-1; i++){
newarr[i] = arr[i];
}
newarr[size-1]=newval;
delete [] arr;
arr = newarr;
}
template <class T>
void EArray<T>::display(){
for(int i = 0; i < size; i++){
cout << arr[i] << endl;
}
}
int main(){
EArray<int> A(6);
A.setElement(0,34);
A.setElement(1,544);
A.setElement(2,32);
A.setElement(3,324);
A.setElement(4,24);
A.display();
A.addElement(3,12);
A.display();
A.eraseElement(4);
A.display();
A.push(32456);
A.display();
}