Link to home
Start Free TrialLog in
Avatar of clscor2
clscor2Flag for United States of America

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!

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);
	}

Open in new window

SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
void load_data();        <--------------------------[ Look, you have a semi-colon here that shouldn't be
{  //**RECEIVE AN ERROR HERE
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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);
}

Open in new window

>> 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 */ }



Avatar of clscor2

ASKER

Thank you