I kept getting incompatible pointer types passing 'char (*)[64]' to parameter of type 'const char **' when I pass the name[100][64] in the sort function and end up getting segmentation fault 11
#define size 100
#define type 10
// Defining comparator function as per the requirement
static int myCompare(const void* a, const void* b){
return strcmp(*(const char**)a, *(const char**)b);
}
void sort(int n, const char* arr){
qsort(arr, n, sizeof(const char*), myCompare);
}
int main(){
int num; scanf("%d", &num);
char name[100][64];
//input
for(int i = 0; i < num; i++){
scanf("%s", name[i]);
}
//sort
sort(num, &name[0]);
}
I have tried char* name[100]; to solve the problem, but still get the warning - segmentation fault 11
char* name[100];
//input
for(int i = 0; i < num; i++){
scanf("%s", name[i]);
}
sort(num, name);
I want to know how to input several strings and sort them like a dictionary.
You declared a character array like
used in expressions like a function argument it is implicitly converted to a pointer to its first element of the type
char ( * )[64].Or if to use this call
then again the expression
&name[0]that is equivalent to the expressionnameused as an argument has the typechar ( * )[64]However the function
sortwhere the array is used as an argument has type of the corresponding parameterconst char **.There is no implicit conversion between the pointer types. And moreover if even to use an explicit casting nevertheless the call will be incorrect because the argument will mean that you are passing an array of pointers. But the function
qsortwill need to swap elements of the typechar[64]instead of elements of the typeconst char *.Your functions can look the following way as shown in the demonstration program below.
The program output is