c++ – Allocate memory in a dynamic array without losing previous data

Question:

Hello!

There is an Employee class and a members dynamic array. At startup, the program reads all objects of the Employee class from the file and adds them to this array:

std::ifstream infodatr("Members.dat", std::ios::out);
while(infodatr.read((char *)&Y, sizeof(Employee)))
{
    AddM();
    members[lich] = Y;
    ++lich;
}

The dynamic array expands on the fly, but that's where I caught the error. When allocating memory for a new slot, I lose all the information that was stored in the array.

void AddM()
{
    try
    {
        members = new Employee;
    }
    catch (std::bad_alloc xa)
    {
        std::cout << "Не удалось добавить в дим. масив " << std::endl;
        system("Pause");
    }
}

How to solve this problem?

Answer:

If you want to expand an array dynamically in the С style, there are a number of things you need to do to do this:

  1. Create a new index
  2. Allocate memory for a new array
  3. Copy all elements of the old array to the new array
  4. Clear old array
  5. Replace pointer to old array with new one

If any C++ tools are available to you, then pay attention to containers of the std::vector .

Scroll to Top