Hey, please try this, and let me know if work. I have never used realloc before, and I am too lazy to make a real program to test it. But this piece of code compiles with the correct headers iostream, fstream and stdlib.h. Any error, that anyone spot, please post...
Hope that helps!
Code:
// This is a simple function that adds a new record, given the file name,
// the buffer, maximum size of the buffer and current index. You can easily
// change this function to add a Record, instead of a file.
// It returns true when add succesfully
bool add_record(Record*& ptr, int& maximum_size, int& current_index, ifstream& file)
{
// If the new record will overflow the buffer
if( current_index+1 > maximum_size )
{
// Temporary pointer
void* t_ptr;
// Realloc memory, adding 5 space for more records at once
t_ptr = realloc(ptr, maximum_size*sizeof(Record) + 5*sizeof(Record));
if(t_ptr != NULL)
{
// If ok, the ptr can receive the new memory
ptr = static_cast<Record*>(t_ptr);
// The maximum_size must be updated
maximum_size = maximum_size + 5;
}
else
{
cerr << "Canīt alloc enough memory, sorry =(" << endl;
return false;
}
}
// Remember that, as our realloc is BEFORE the read,
// current index must be initialized at -1.
current_index++;
file.read( (char *) &ptr[current_index], sizeof(Record));
return true;
}