jeudi 25 mai 2017

Why is my program crashing at this one line?

#include <iostream>

using namespace std;
template <class T>
class myset{
private:
T *pArray;
int size;

public:
    myset<T>(){
    pArray = new T[0];
    int size =0;
    }
    void addItem(T iVal){
    size++;
    T* newArray = new T [size];// allocate bigger array //
    for(int i=0; i< size-1; i++){
        newArray[i] = pArray[i]; // IT IS CRASHING BECAUSE OF THIS LINE
    }
    pArray[size -1] = iVal;
    pArray = NULL;
    pArray = newArray;
}
};
int main()
{
    myset<int> a;
    myset<double> d;
    a.addItem(3);
    a.addItem(5);
}

What I am trying to do is making a dynamic array of any template. In my add function, I am trying to copy my old array into my new array. Can anyone tell me why it is not working?

Aucun commentaire:

Enregistrer un commentaire