I am writing the following array (class) that increases the size when index of this array is bigger than size of this array. I know about vectors but it has to be array. The Code looks like this:
#include <iostream>
using namespace std;
class Array {
public:
Array():_array(new float[0]), _size(0){};
~Array() {delete[] _array;}
friend ostream &operator<<(ostream&,const Array&);
float& operator[] (int index)
{
if(index>=_size)
{
float* NewArray=new float[index+1];
for(int i=0;i<_size;++i) NewArray[i]=_array[i];
for(int i=_size;i<index+1;++i) NewArray[i]=0;
delete[] _array;
_array=NewArray;
_size=index+1;
}
return _array[index];
}
private:
float *_array; // pointer to array
int _size; // current size of array
};
ostream &operator << ( ostream &out, const Array& obj) // overloading operator<< to easily print array
{
cout << "Array:\n\n";
for (int i=0;i<obj._size;++i)
{
cout << obj._array[i];
if(i+1!=obj._size) cout << ", ";
}
cout << ".\n";
return out;
}
int main()
{
Array CustomArray;
CustomArray[2] = CustomArray[1] = CustomArray[0] = 3.14; // **here is the problem**
cout << CustomArray << endl;
}
Everything is ok, 0 warnings , 0 valgrind errors, output :
3.14, 3.14, 3.14.
BUT i have to write this code ( in main ) this way :
CustomArray[0] = CustomArray[1] = CustomArray[2] = 3.14;
and now it's 3 valgrind errors: Address (some_address) is 4 bytes inside a block of size 8 free'd,
and output looks like that : 0, 0, 3.14.
unfortunately i have to write this code to work the second way
( CustomArray[0] = CustomArray[1] = CustomArray[2] = 3.14; )
Can you guys help ? Thanks in advance
CustomArray[1]invalidates all previous references and pointers to data because it is reallocated. What you may do is a return anArrayAccessthat holds the index and doesn't hold a reference but accesses the original array everytime.std::vectorcould cope with that if one of thoseoperator[]calls causes a reallocation...