user1215882
user1215882

Reputation: 5

How can I delete a non-dynamically allocated array in C++?

The reason why I ask is because I am using a non-dynamically allocated array for my hashtable; however, for my rehash function in my hashtable, I need to be able to change the size of my old array. How can I do this?

Upvotes: 0

Views: 757

Answers (5)

valdo
valdo

Reputation: 12951

There are dozens of ways to handle this out. Of course "deallocating" a memory that was not allocated on the heap - is the worst hack to imagine.

I may suggest something like this:

class MyClass
{
   TableEntry* m_pStaticTable[/* some size */];

   TableEntry* m_pActualTable;
   size_t m_nSize;

   MyClass()
      :m_pActualTable(m_pStaticTable)
      ,m_nSize(_countof(m_pStaticTable))
   {
   }

   ~MyClass()
   {
      if (m_pActualTable != m_pStaticTable)
         delete[] m_pActualTable;
   }

};

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64308

Assuming you have something like this:

TableEntry table[max_table_size];

you are going to need a separate variable that indicates how much of the array you are actually using:

size_t table_size = 0;

and then you just use that variable instead of trying to resize the actual array.

Upvotes: -1

Doug T.
Doug T.

Reputation: 65649

If you want to manually control the lifetime of memory, you need to use dynamic memory allocation. Non-dynamically allocated memory (statically allocated) will only be deallocated when the memory goes out of scope. Since this memory lives in the object your managing, that memory only goes out of scope when the owning object in deallocated.

So you will need to dynamically allocate a buffer at construction then when resizing allocate a new buffer, copy the contents from the old buffer into the new buffer, delete the old buffer, then assign your object's internal pointer to the new buffer. Something like:

// allocate a new, bigger array
Cell* newBuff = new Cells[/*newSize*/];

// copy into the new array
for (i = 0; i < myBufferSize; ++i)
{
   newBuff[i] = myBuffer[i];
}
// delete the old array
delete myBuffer;
// point to the new array
myBuffer = newBuff;

Could you base your hash table on a std::vector instead of using manual memory allocation? This will handle the dynamic array for you, and you can resize with a simple .resize:

myBuffer.resize(/*newSize*/)

Upvotes: 1

Matthias
Matthias

Reputation: 8180

Short answer: you can't.

A longer answer would introduce very dirty and os-dependent hacks.

Upvotes: 3

Philipp
Philipp

Reputation: 49850

If you want to change the size, you have to allocate it dynamically, preferably using std::vector.

Upvotes: 3

Related Questions