习题 8.20 用指向指针的指针的方法对5个字符串排序并输出。

C程序设计(第四版) 谭浩强 习题8.20 个人设计

习题 8.20 用指向指针的指针的方法对5个字符串排序并输出。

代码块:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *s[5], int n);         //定义排序函数
int main()
{
    char *str[5], **p;
    int i;
    for (i=0; i<5; str[i++]=(char *)malloc(20*sizeof(char)));                       //分配字符串空间
    for (p=str, printf("Please enter 5 strings: "); p<str+5; scanf("%s", *p++));    //输入5个字符串
    sort(str, 5);                                                                   //定义排序函数
    for (p=str, printf("Sort by: "); p<str+5; printf("%s ", *p++));                 //输出排序后的5个字符串
    printf("\n");
    return 0;
}
//排序函数
void sort(char *s[5], int n)
{
    int i, j;
    char *t;
    for (i=0; i<n; i++)
        for (j=i+1; j<n; strcmp(s[i], s[j])>0 ? t=s[i], s[i]=s[j], s[j]=t, j++ : j++);
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/79449285
今日推荐