I am having a problem trying to use realloc to grab an extra chunk of memory for a struct (as a record structure). I already have one struct set up and "filled in". My problem is that I cannot seem to visualize how to calculate the number of records currently in the preseently used chunk of memory. The idea is that function addRecord() will calculate how many records currently exist and then grab an extra chunk of memory (using realloc) for one more record each time it is called.
Here is my struct:
typedef struct rec
{
char recordUsed;
char firstName[15];
char lastName[15];
char phoneNumber[15];
} record;
Now here is the current (offending) code:
unsigned int addRecord(record * theseRecords)
{
record * tempRecord;
/* **Problem lies in next line** */
unsigned int numberOfRecords = sizeof(theseRecords) / sizeof(record);
/* Use the realloc() function to add contiguous memory segments to the *
* original memory block when a user adds a new phone book entry. */
tempRecord = (record *) realloc(theseRecords, ++numberOfRecords * sizeof(record));
if (tempRecord == NULL) /* If memory not available ... */
{
printf("\nERROR! Out of memory!\n");
return 0; /* ... exit program */
}
theseRecords = tempRecord; /* Capture possible new pointer */
printf("\n\tAdd Record\n");
fillRecord(theseRecords);
}
As requested, here is the main() function that calls the addRecord() function.
int main()
{
record * theRecords;
char response;
theRecords = createFirstRecord();
if (theRecords == NULL) /* If memory not available then ... */
{
printf("\nERROR! Out of memory!");
return 0; /* ... exit program */
}
showTopMenu();
scanf(" %c", &response);
response = toupper(response);
while (response != 'Q')
{
switch (response)
{
case 'A': addRecord(theRecords);
break;
case 'E': editRecord(theRecords);
break;
} /* end switch() */
showTopMenu();
scanf(" %c", &response);
response = toupper(response);
} /* end while() */
return 0;
}
I am aware that the line in which the number of records is calculated is utter rubbish in that it attempts to divide a pointer with an int. My problem is that I just can't seem to "see" how to do this calculation. Specifically, with what do I replace "sizeof(theseRecords)" ?
Stuart