Hello: i have a problem about the loop
this problem is fine when the number of name is less than 3
after the num >=4 , after showing the unsorted output, it doesnt show the sorted one. i dunno what wrong with my program . Plz help.. thank you
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define merror() {printf("memory allocation problem\n");exit(1);}
int main(void)
{
char buffer[2];
char **buf;
char *sto;
int num;
int i, j;
A: printf(" how many names will be entered : \n");
fflush(stdout);
fgets ( buffer, 10, stdin );
num = atoi (buffer);
if (num <=0)
{
printf("empty input \n");
}
else if (num >100)
{
printf("input too long \n");
goto A;
}
else if (num >0 && num <= 100)
{
printf("you will enter %d names \n", num);
}
for(i=0; i<num; i++)
{
buf[i] = malloc(sizeof(char*));
}
for(i=0; i < num; i++)
{
printf(" enter a name \n");
for(j=0; j<21; j++)
{
buf[i][j]=fgetc(stdin);
if (buf[i][j]=='\n') {
buf[i][j]='\0';
break; /* break j-loop */
}
}/* end j-loop */
if (j==21)
{
printf("input too long\n");
while(fgetc(stdin)!='\n');
continue; /* continue i-loop */
}
}
printf("\nunsorted input:\n");
for(i=0; i< num; i++)
printf("%s\n", buf[i]);
sto = malloc(sizeof(char*));
for(i=num; i>0; i--)
{
for(j=0; j<i; j++)
if (strcmp(buf[j],buf[j+1])>0)
{
sto=buf[j];
buf[j]=buf[j+1];
buf[j+1]=sto;
}
}
printf("sorted input:\n");
for(i=0; i<num; i++)
{
printf("%s\n",buf[i]);
}
free(buf);
free(sto);
return 0;
}