Practice learning the API. If you sort the array including blank elements in ascending order, The blank comes to the beginning.
If you don't want whitespace to be included in the comparison Sort by specifying the length of the array.
qsort(table, 4, sizeof(table[0]), compare_char);
Part 4 of is applicable.
qsort.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare_char(const void* left, const void* right) {
char *left_char = (char *)left;
char *right_char = (char *)right;
return strcmp( left_char, right_char );
}
int main() {
int i=0;
char table[10][20] = {
"123",
"A0",
"Z0",
"9w3"
};
for(i=0; i<10; i++) {
printf("%d %s\n", i, table[i]);
}
printf(" --- sort\n");
qsort(table, 4, sizeof(table[0]), compare_char);
for(i=0; i<10; i++) {
printf("%d %s\n", i, table[i]);
}
}
In response to the comment pointed out, it has been modified so that the comparison function of the called destination receives the type information of the object accurately. In addition, the code was modified so that the end of the array can be defined with NULL
and the end of the character array can be detected.
qsort-withPointer.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare_char(const void* left, const void* right) {
const char *left_char = *(const char **)left;
const char *right_char = *(const char **)right;
return strcmp( left_char, right_char );
}
int main() {
int i=0;
//Equivalent to placing a string literal in an array
const char* s0 = "123";
const char* s1 = "A0";
const char* s2 = "Z0";
const char* s3 = "9w3";
//Guard at the end of the array(NULL)Place
const char* table[] = {s0, s1, s2, s3, NULL};
printf(" --- original\n");
// table[]Count the elements of
//Increment the counter until it finds a null that represents the end of the array
i=0;
while(table[i]) {
printf("%d %s\n", i, table[i]);
i++;
}
printf(" --- sort\n");
qsort(table, i, sizeof(*table), compare_char);
i=0;
while(table[i]) {
printf("%d %s\n", i, table[i]);
i++;
}
}
Recommended Posts