NotAlpha102

Use of qsort

Jul 30th, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4.  
  5. int compare(const void* a, const void* b)
  6. {
  7.     const char *ia = (const char *)a;
  8.     const char *ib = (const char *)b;
  9.     return strcmp(ia, ib);
  10. }
  11.  
  12. main()
  13. {
  14.     /*str is a pointer that points to pointers that points to strings*/
  15.     char **str;
  16.  
  17.     /*i will denote how much memory we should take for now.
  18.     Start from 1*/
  19.     int i=1;
  20.     str=(char**)malloc(sizeof(char*)*i);
  21.     while(1)
  22.     {
  23.         str[i-1]=(char*)malloc(sizeof(char)*21);
  24.         gets(str[i-1]);
  25.         if(strlen(str[i-1])==0 && str[i-1][0]==0)
  26.             break;
  27.  
  28.         //Increment i to account for more memory.
  29.         i++;
  30.  
  31.         /*make the memory size larger again*/
  32.         str=(char**)realloc(str, sizeof(char*)*i);
  33.     }
  34.  
  35.  
  36.  
  37.     printf("%d\n", sizeof(str));
  38.  
  39.     qsort(str, i-1, sizeof(str[0]),compare);
  40.  
  41.  
  42.     for(int itr=0; itr<i-1; itr++)
  43.     {
  44.         printf("%s\n", str[itr]);
  45.     }
  46.  
  47.     free(str);
  48.  
  49.  
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment