-
while loop
im Hi im trying to understand this sorting program and im not sure why in this example
in the while loop there checking for NULL twice in the while condition
Code:
#define SIZE 81 /*string length including \0*/
#define LIM 20 /*maximun number of lines to be read*/
#define HALT "" /*null string to stop input*/
void stsrt(char *strings[], int num); /*string sort function*/
int main(void)
{
char input[LIM][SIZE];/*array to store input*/
char *ptstr[LIM]; /*array of pointer variables*/
int ct = 0; /*input count*/
int k;/*output count*/
printf("Input up to %d lines and i will sort them\n", LIM);
printf("To stop, press the enter key at a lines start\n");
while(ct <LIM && gets(input[ct])!=NULL
&& input[ct][0] != '\0')
{
ptstr[ct] = input[ct]; /*set pointers to strings*/
ct++;
}
stsrt(ptstr, ct); /*string sorter*/
puts("Here's the sorted list\n");
for(k=0; k<ct; k++)
{
puts(ptstr[k]); /*sorted pointers*/
}
return EXIT_SUCCESS;
}
void stsrt(char *strings[], int num)
{
char *temp;
int top, seek;
for(top = 0; top < num -1; top++)
{
for(seek = top + 1; seek < num; seek++)
{
if(strcmp(strings[top], strings[seek])>0)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
}
}
}
-
Code:
while(ct <LIM && gets(input[ct])!=NULL && input[ct][0] != '\0')
is not "checking for NULL twice".
After checking ct < LIM, it then checks if gets(input[ct]) has returned a NULL pointer (which indicates that gets() has encountered an error reading from stdin). If a NULL pointer has not been returned, it checks if the first character read is zero (which indicates that input was received by gets() before a '\n' was encountered).
Essentially, this means the loop read one line at a time until an error occurs, or until a line is entered with no text (eg "Enter" key is hit twice).
Unrelated to your question, use of gets() is not a good idea because it will happily yield undefined behaviour (typically tromping random memory locations) if the user enters a long line.