Yonka2019

question2.c

May 4th, 2021 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.79 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. #define SIZE 50
  8.  
  9. void sort(const char* arr[], int n);
  10. void myFgets(char str[], int n);
  11. int myCompare(const void* a, const void* b);
  12.  
  13. int main()
  14. {
  15.     int friendsNumber = 0, i = 0;
  16.     char str[SIZE] = { 0 };
  17.     char** names;
  18.  
  19.     printf("Enter number of friends: ");
  20.     scanf("%d", &friendsNumber);
  21.     getchar();
  22.    
  23.     names = (char**)malloc(sizeof(char*) * friendsNumber); //allocating size to the pointer (to another arrays..)
  24.  
  25.     for (i = 0; i < friendsNumber; i++)
  26.     {
  27.         printf("Enter name of friend %d: ", i + 1);
  28.         myFgets(str, SIZE);
  29.        
  30.         names[i] = (char*)malloc(sizeof(char) * strlen(str) + 1); //allocating size to EACH pointer (array) (by the name (str) length)
  31.  
  32.         strcpy(names[i], str);
  33.     }
  34.     sort(names, friendsNumber);
  35.     for (i = 0; i < friendsNumber; i++)
  36.     {
  37.         printf("Friend %d: %s\n", i + 1, names[i]);
  38.         free(names[i]);
  39.     }
  40.  
  41.     free(names);
  42.  
  43.     getchar();
  44.     return 0;
  45. }
  46. /*
  47. * Full fgets() function
  48. * input: string to input, string length
  49. * output: -
  50. */
  51. void myFgets(char str[], int n)
  52. {
  53.     fgets(str, n, stdin);
  54.     str[strcspn(str, "\n")] = 0;
  55. }
  56. /*
  57. * Defining comparator function as per the requirement
  58. * input: two constans to compare
  59. * output:
  60.  
  61.     Return value < 0 then it indicates a is less than b.
  62.  
  63.     Return value > 0 then it indicates b is less than a.
  64.  
  65.     Return value = 0 then it indicates a is equal to b.
  66.  
  67. */
  68. int myCompare(const void* a, const void* b)
  69. {
  70.     return strcmp(*(const char**)a, *(const char**)b);
  71. }
  72. /*
  73. * Function to sort the array
  74. * input: array to sort, array size (length)
  75. * output: -
  76. */
  77. void sort(const char* arr[], int n)
  78. {
  79.     // calling qsort function to sort the array
  80.     // with the help of Comparator
  81.     qsort(arr, n, sizeof(char*), myCompare);
  82. }
Add Comment
Please, Sign In to add comment