#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_REMIND 50
#define MSG_LEN 60
int 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 字符串数组*/
}
qsort()方法作用于字符串数组的范例
最新推荐文章于 2022-01-14 22:20:35 发布