Thursday, May 31, 2012

String Sorting Program in C (uses array of pointers to store strings)

/* string sorting program the logic may be simple but I have used array of pointers here to store the strings
crucial here is u should you malloc and calloc to get 
correct output(because array of pointers are used)*/ #include stdio.h #include string.h #define MAX 50 void main() { char *names[MAX],*dummy; int i=0,j=0,n=0; clrscr(); puts("enter no. of strings you want to enter"); scanf("%d",&n); printf("please enter %d strings\n\n",n);
for(i=0;i { names[i]=malloc(12); scanf("%s",names[i]); } for(i=0; i { for(j=i+1; j { if((strcmp(names[i],names[j])) > 0) { strcpy(dummy,names[i]); strcpy(names[i],names[j]); strcpy(names[j],dummy); } } } printf("\nstrings are sorted--\n"); for(i=0; i { printf("\n%s\n",names[i]); free(names[i]); } getch(); }

No comments:

Post a Comment