Can you redim an array in C++.
// I need 10 integers
int *pInteger = new int[10];
// Oops, now I need to store 11
Can you allocate memory at the end of this block, or would you need to
create a new array, copy the old contents, delete the old array?
Does the question make sense?
Reallocation is not possible as the others have already pointed out. You
either go for vector, which would be the solution I would recommend in
general, or you could use the following template for PODs.
template<class T>
void GetMem(T*& OldMem, int Elems)
{
typedef int cntr; // Type of element cntr
const int CountSize = sizeof(cntr); // And size
const int TypeSize = sizeof(T);
if( Elems == 0) {
free( &(((cntr*)OldMem)[-1]) );
return;
}
T* p = OldMem;
cntr OldCount = 0;
if(p) { // Previously allocated memory
cntr* tmp = reinterpret_cast<cntr*>(p);
p = reinterpret_cast<T*>(--tmp);
OldCount = *(cntr*)p; // Previous # Elems
}
T* m = (T*)realloc(p, Elems * TypeSize + CountSize);
assert(m != 0);
*((cntr*)m) = Elems; // Keep track of count
const cntr Increment = Elems - OldCount;
if( Increment > 0) {
// Starting address of data:
long StartAdr = (long)&(m[OldCount]);
StartAdr += CountSize;
// Zero the additional new memory:
memset((void*)StartAdr, 0, Increment * TypeSize);
}
// Return the address beyond the count:
OldMem = (T*)&(((cntr*)m)[1]);
}
This would allow you to do for example this:
int* p = 0;
GetMem(p, 10);
for(int i = 0; i < 10; i++) {
cout << p
<< ' ';
p = i;
}
cout << '\n';
// now I need more elements
GetMem(p, 20);
for(int j = 0; j < 20; j++) {
cout << p[j] << ' ';
p[j] = j;
}
HTH
Chris