Hi guys, I'm trying to load the contents of a file I am writing into dynamic memory. What I was thinking is have an array, of which each element holds a pointer to a struct which contains information on different types of people.
the struct I am holding it in is something like this:
Code:
struct StudentRecord
{
char* firstName; // student key
char* lastName; // student name
int id; // student id
float mark; // course mark
};
in main, I have
Code:
struct StudentRecord ** Records;
int numRecords = 0;
my function will read from file (already opened), and dynamically allocate the lengths of names, as well as the array will grow as needed. my question is regarding resizing the array...
Sinc each element is a pointer to a structure, I will use another array which will grow each time the array is filled (by a factor of 2) to copy the existing array, resize it, then copy it back, after which deleting it. I think I've got it figured out, but am wondering about some tweaks:
Here's the code, and a couple questions to follow:
Code:
bool LoadFileToMemory(ifstream& fin, StudentRecord**& Records, int& numRecords)
{
char * firstName;
char * lastName;
int size = 10; //an initial size for the StudentRecord array
struct StudentRecord ** tempRecords;
Records = new StudentRecord*[size];
while(!fin.eof())
{
if((size -1) == numRecords)
{
tempRecords = new StudentRecord*[size];
for(int i = 0; i < numRecords; i++)
tempRecords[i] = Records[i];
size += size;
Records = new StudentRecord*[size];
for (i = 0; i < numRecords; i++)
Records[i] = tempRecords[i];
}
if(!fin >> firstName >> lastName)
{
cerr << "Failed to read from file...\n";
return false;
}
Records[numRecords] = new struct StudentRecord;
Records[numRecords]->firstName = new char[strlen(firstName) + 1];
strcpy(Records[numRecords]->firstName,firstName);
Records[numRecords]->lastName = new char[strlen(lastName) + 1];
strcpy(Records[numRecords]->lastName,lastName);
if(!fin >> Records[numRecords]->id >> Records[numRecords]->mark)
{
cerr << "Failed to read from file...\n";
reteurn false;
}
numRecords += 1;
}
//delete the temporary array of pointers
delete [] tempRecords;
return true;
}
1) Would just resizing the array by one be more efficient than this approach, as I wouldn't have to keep track of the size of the array versus doubling it each time, to not have to enter the two for loops as often?
2) Is there a better way of loading from a file to memory?