qsort()方法作用于字符串数组的范例
来源:互联网 发布:windows系统怎么录屏 编辑:程序博客网 时间:2024/05/01 23:11
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_REMIND 50#define MSG_LEN 60int read_line(char str[], int n);int compare_parts(const void *p, const void *q);int main(void){ char *reminders[MAX_REMIND]; char msg_str[MSG_LEN+1]; int num = 0, i; for (;;) { printf("Enter word: "); if (read_line(msg_str, MSG_LEN) == '\0') break; reminders[num] = malloc(strlen(msg_str)); if (reminders[num] == NULL) { printf("-- No space left --\n"); break; } strcpy(reminders[num], msg_str); num++; } puts(""); qsort(reminders, num, sizeof(reminders[MSG_LEN]), compare_parts); /* Si deve scritto sizeof(reminders[MSG_LEN]) */ printf("In sorted order: "); for (i = 0; i <num; i++) printf("%s ", reminders[i]); puts(""); return 0;}int read_line(char str[], int n){ int ch, i = 0; while ((ch = getchar()) != '\n') if (i < n) str[i++] = ch; str[i] = '\0'; return i;} int compare_parts(const void *p, const void *q){ return strcmp(*(char **) p, *(char **) q); /* Si deve fare il doppio *,poi fa singolo *, per il 字符串数组*/}