I'm experimenting with fgets because I heard it's better for dealing with memory buffer overflow but I am not sure of the sizeof component and how to the stdin part helps it to work. Is METHOD 1 or METHOD 2 in the following code the correct implementation of sizeof and what does stdin do exactly in the fgets.

// Data Structure
typedef struct{
   char first_name[20];
   char middle_name[20];
   char last_name[20];
   char illness_type[5];
   int patient_number;
   char doctor_fname[20];  // Doctor's First Name
   char doctor_lname[20];  // Doctor's Last Name
	char emer_fname[20];    // Emergency Contact's First Name
	char emer_lname[20];		// Emergency Contact's Last Name
   int emer_telephone;     // Emergency Contact's Number
}	PATIENT_DATA;

// Defining data type
PATIENT_DATA section_1[40]={"","","","",0,"","","","",0};

//METHOD 1
printf("\nPatient First Name: ");
fflush(stdin);
fgets(section_1[tally1].first_name, sizeof section_1[tally1].first_name, stdin);

//METHOD 2
printf("\nPatient First Name: ");
fflush(stdin);
fgets(section_1[tally1].first_name, sizeof section_1[20].first_name, stdin);

line 20: fflush() is only defined with output streams such as stdout. What you have is undefined behavior. Since the line about is an output line maybe you meant to use stdout instead of stdin.

either line 21 or 26 will work, as well as this: fgets(section_1[tally1].first_name, sizeof ((PATIENT_DATA*)0)->first_name, stdin); The reason the above works without crashing the program is because the sizeof operator is evaluated at compile time, not runtime. So the above is not really dereferencing a NULL pointer.

When I use stdout the program does not allow me to enter the Patient's Name but simply moves on...

I know those two methods will work but I want to understand what the real difference between them is and how it affects to overall program in terms of efficient coding.

>>When I use stdout the program does not allow me to enter the Patient's Name but simply moves on...
In that case the problem is elsewhere in some code that you didn't post. Most likely using scanf() to get a numerical data entry. After that call getchar() to extract the '\n' key that scanf() leaves in the keyboard buffer.

>> I want to understand what the real difference between them
Nothing, they are equavilant.

>>how it affects to overall program in terms of efficient coding.
It does nothing for that -- completly up to you which way you want to do it. The compiler could care less and the results are identical.

This article has been dead for over six months. Start a new discussion instead.