clscor2
asked on
Array of Structs and Realloc
Part of an assignment is to create to .dat files, such as vehicles.dat and rentalsl.dat. Then, once a file is open, data is read into an array of structs, using the realloc library function to dynamically create sufficient memory for each user entry read from the file.
I've gotten this far, but I'm a bit stuck. Any help would be appreciated!
I've gotten this far, but I'm a bit stuck. Any help would be appreciated!
void load_data();
{ //**RECEIVE AN ERROR HERE
int count=0, file_end=0;
FILE* file_ptr=fopen("vehicles.dat", "r");
FILE* file_ptr_2=fopen("rentals.dat", "r");
printf("\n%20s%10s%10s\n", "VEHICLE TYPE", "VEHICLE CLASS", "REGISTRATION");
do
{
file_end=fscanf(file_ptr, "%s%s%d", temp_vehicle.type, temp_vehicle.cls, &(temp_vehicle.reg));
if (file_end != EOF)
{
printf("\n%20s%10s%10d", temp_vehicle.type, temp_vehicle.cls, &temp_vehicle.reg);
count++;
}
}
while (file_end != EOF);
fclose(file_ptr);
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Oops I forgot to increment cnt :)
#include <malloc.h>
#include <memory.h>
typedef struct { int nSomeMember; } foo;
int ReadFromFile(foo * pFoo) // Just a dummy function to allow the exmaple to build
{
// Read a record from file and populate the object pointed to by pFoo;
return 1; // Return false where no more records to process
}
int main()
{
foo * pFoo = 0;
size_t cnt = 0;
foo f;
f.nSomeMember = 0;
while(ReadFromFile(&f))
{
pFoo = realloc(pFoo, cnt + 1); // Extend foo array
if(pFoo)
{
// add foo to array
memcpy(&pFoo[cnt++], &f, sizeof(f));
}
else
{
// error
}
}
// Now clean up
free(pFoo);
}
>> pFoo = realloc(pFoo, cnt + 1)
Should be
pFoo = realloc(pFoo, sizeof(Foo) * cnt + 1);
Also... when using realloc you should initally assign the return value to a new pointer and not overwrite the old one (as I have done above). The reason for this is if memory cannot be allocated then realloc returns NULL, but the original memory is not freed so if you just overwrite the original pointer you'll leak memeory.
int * porig = calloc(10, sizeof(int));
int * pnew = realloc(porig, sizeof(int) + 20);
if(pnew) { porig = pnew; }
else { /* problem */ }
Should be
pFoo = realloc(pFoo, sizeof(Foo) * cnt + 1);
Also... when using realloc you should initally assign the return value to a new pointer and not overwrite the old one (as I have done above). The reason for this is if memory cannot be allocated then realloc returns NULL, but the original memory is not freed so if you just overwrite the original pointer you'll leak memeory.
int * porig = calloc(10, sizeof(int));
int * pnew = realloc(porig, sizeof(int) + 20);
if(pnew) { porig = pnew; }
else { /* problem */ }
ASKER
Thank you
{ //**RECEIVE AN ERROR HERE