习题 8.12 用指针数组处理上一题目,字符串不等长。

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

习题 8.12 用指针数组处理上一题目,字符串不等长。

代码块:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *s[10], int n);       //定义排序函数
int main()
{
    char *str[10], **p;
    for (int i=0; i<10; i++){
        str[i]=(char *)malloc(20*sizeof(char));      //为指针数组分配内存动态空间
        printf("Please enter No.%d string: ", i+1);  //输入10个字符串
        scanf("%s", str[i]);
    }
    sort(str, 10);                                   //调用排序函数
    for (p=str, printf("Sort by: "); p<str+10; printf("%s ", *p++));    //输出排序后的10个字符串
    printf("\n");
    return 0;
}
//排序函数
void sort(char *s[10], 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/79412145