Below is the code(unchanged) of a question I encountered while solving hackerrank questions:
But i couldnot understand 3 lines which i have marked as number 1,2 and 3 in the below code.
As the program flows from main to func's
Lets look at 3 first:
We are passing a function name lexicographic_sort as one of the parameter to string_sort function.
Now lets have a look at 1 and 2:
In function string_sort
lexicographic_sort is passed as int (cmp_func)(const char a, const char b)*
1st doubt: what is cmp_func, it is not defined anywhere, is it a sytem defined function?
2nd doubt: we are not passing any parameters which would go into char* a, char* b. What would go to their values?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
1. int lexicographic_sort(const char* a, const char* b) {
}
int lexicographic_sort_reverse(const char* a, const char* b) {
}
int sort_by_number_of_distinct_characters(const char* a, const char* b) {
}
int sort_by_length(const char* a, const char* b) {
}
2. void string_sort(char** arr,const int len,int (*cmp_func)(const char* a, const char* b))
{
}
int main()
{
int n;
scanf("%d", &n);
char** arr;
arr = (char**)malloc(n * sizeof(char*));
for(int i = 0; i < n; i++){
*(arr + i) = malloc(1024 * sizeof(char));
scanf("%s", *(arr + i));
*(arr + i) = realloc(*(arr + i), strlen(*(arr + i)) + 1);
}
3. string_sort(arr, n, lexicographic_sort);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, lexicographic_sort_reverse);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, sort_by_length);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
string_sort(arr, n, sort_by_number_of_distinct_characters);
for(int i = 0; i < n; i++)
printf("%s\n", arr[i]);
printf("\n");
}