This is c language and I have a file which I want to read it tothis array of poi
ID: 3612775 • Letter: T
Question
This is c language and I have a file which I want to read it tothis array of pointers to structure. I have 2 doctors and 3patients, and the clinic I want to read and store it to thestructure objects, so this is how it is:#include<stdio.h>
struct doctors
{
char firstname[20];
char lastname[20];
int operationid;
};
struct patients
{
char firstname[20];
char lastname[20];
int chosendocid;
};
struct clinic
{
char clinicname[25];
struct doctors *ptr[2]; //an array of pointers to objects of the doctor structure
struct patients *pat[3] //an array of pointers to objects of the patient structure
//I can only use this array of pointers.
};
void recursivealloc_mem(FILE *notefile, struct patients, intrec);
int main(void)
{
FILE *notefile;
struct clinichosp; //I can only declare this two localvaluables,
int rec=2;
notefile =fopen("file1.dat", "r");
if(notefile == NULL)
{
printf("file1.dat file does not exist ");
return(-1);
}
recursivealloc_mem( notefile, &hosp, rec);
fclose(notefile);
}
void recursiveallocdoc_mem(FILE *notefile, struct clinic *xhosp,int rec)
{
int index, xindex =1;
if(xindex <= rec)
recursiveallocdoc_mem(rec - 1);
xhosp->doc[rec] = malloc(3 * sizeof( struct doctor));
for(index=0;index<2;index++)
{
fscanf(notefile, "%s %s %d ",xhosp->doc[i]->firstname,xhosp->doc[i]->lastname, xhosp->doc[i]->id);
printf("%s, %s,%d ",xhosp->doc[i]->firstname,xhosp->doc[i]->lastname, xhosp->doc[i]->id);
}
}
}
And the file I have written so far is:
James
Warren
3542
Maud
Spearman
2267
Ike
Williams
2267
Caleb
Walker
3542
I am trying to let the program read and store it by allocatingmemory recursively, that's the one it's giving me problems becauseI don't understand array of pointers to structures very well.Please I can only declare the structure objects like it is. Soplease how can I recursively allocate memory for it?
Explanation / Answer
when accesing the data through variables of structure we use dotoperator but in case of pointer variables of structure we use thearrowhead operator like here first u need to allocate memory to the pointer variablewhich can be done by::: hosp.ptr[0] = new struct clinic hosp.pat[0]= new struct patients then acces the data members by using the arrow operator like hosp.ptr[0]->firstname hosp.pat[0]->firstname
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.