C程序设计(第四版) 谭浩强 习题8.11 个人设计
习题 8.11 在主函数中输入10个等长的字符串。用另一函数对它们排序。然后在主函数输出这10个已排好序的字符串。
代码块:
#include <stdio.h>
#include <string.h>
void sort(char (*s)[10], int n); //定义排序函数
int main()
{
char n[10][10], (*p)[10];
for (p=n, printf("Please enter 10 strings: "); p<n+10; scanf("%s", *p++)); //输入10个字符串
sort(n, 10); //调用排序函数
for (p=n, printf("Sort by: "); p<n+10; printf("%s ", *p++)); //输出10个字符串
printf("\n");
return 0;
}
//排序函数
void sort(char (*s)[10], int n)
{
int i, j;
char t[10];
for (i=0; i<n; i++)
for (j=i+1; j<n; strcmp(*(s+i),*(s+j))>0?strcpy(t, *(s+i)),strcpy(*(s+i), *(s+j)),strcpy(*(s+j), t),j++:j++);
}