I am trying to make a very basic copy of a vector.
when i add too many elements to the vector..all the sudden randomly it starts to behave strangely...only explanation is that maybe i am not understanding how references pass (?)
Heres a part of the code pertaining to my error...
(erased nonessential methods for forum)
Code:
//myVector.h
template <class T>
class myVector
{
public:
myVector(const int sz = 10);
void add(const T&);
T operator[] (int index){ return arr[index]; }
private:
int avail;
T *arr;
void expand();
};
template <class T>
template <class T>
myVector<T>::myVector(const int sz = 10)
{
avail = 0;
arr = new T[sz];
}
template <class T>
void myVector<T>::add(const T &in)
{
//check to see if arr array is full, if it is then call expand function.
if( sizeof(arr) == avail)
{
expand();
}
arr[avail] = in;
++avail;
}
template <class T>
void myVector<T>::expand()
{
const int sz = sizeof(arr);
T temp[sz];
for(int i=0;i<sz;++i)
temp[i] = arr[i];
arr = new T[sz*2];
for(int i=0;i<sz*2;++i)
arr[i]=temp[i];
}
Now here is the code I am testing with it...(there are no compile errors in this program)
and here is the output following it.
Code:
#include <iostream>
#include "myVector.h"
using namespace std;
int main()
{
myVector<int> al(1000);
al.add(5);al.add(5);al.add(5);al.add(5);al.add(5);al.add(5);
al.add(5);al.add(5);al.add(5);al.add(5);al.add(5);al.add(5);
cout << "size : " << al.size()<< endl;
for(int i=0;i<al.size();++i){
cout << al[i]<<endl;
}
}
size : 12
5
5
5
5
5
5
5
5
5
5
1444607057
5
It added a random LARGE number to the 11th slot there..(every time)
If i add one more addition to myVector..the program crashes on runtime...
what is the problem?
thank you