Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define SIZE 50
- void sort(const char* arr[], int n);
- void myFgets(char str[], int n);
- int myCompare(const void* a, const void* b);
- int main()
- {
- int friendsNumber = 0, i = 0;
- char str[SIZE] = { 0 };
- char** names;
- printf("Enter number of friends: ");
- scanf("%d", &friendsNumber);
- getchar();
- names = (char**)malloc(sizeof(char*) * friendsNumber); //allocating size to the pointer (to another arrays..)
- for (i = 0; i < friendsNumber; i++)
- {
- printf("Enter name of friend %d: ", i + 1);
- myFgets(str, SIZE);
- names[i] = (char*)malloc(sizeof(char) * strlen(str) + 1); //allocating size to EACH pointer (array) (by the name (str) length)
- strcpy(names[i], str);
- }
- sort(names, friendsNumber);
- for (i = 0; i < friendsNumber; i++)
- {
- printf("Friend %d: %s\n", i + 1, names[i]);
- free(names[i]);
- }
- free(names);
- getchar();
- return 0;
- }
- /*
- * Full fgets() function
- * input: string to input, string length
- * output: -
- */
- void myFgets(char str[], int n)
- {
- fgets(str, n, stdin);
- str[strcspn(str, "\n")] = 0;
- }
- /*
- * Defining comparator function as per the requirement
- * input: two constans to compare
- * output:
- Return value < 0 then it indicates a is less than b.
- Return value > 0 then it indicates b is less than a.
- Return value = 0 then it indicates a is equal to b.
- */
- int myCompare(const void* a, const void* b)
- {
- return strcmp(*(const char**)a, *(const char**)b);
- }
- /*
- * Function to sort the array
- * input: array to sort, array size (length)
- * output: -
- */
- void sort(const char* arr[], int n)
- {
- // calling qsort function to sort the array
- // with the help of Comparator
- qsort(arr, n, sizeof(char*), myCompare);
- }
Add Comment
Please, Sign In to add comment