1 题目
函数:sort()
功能:使用指向指针的指针对字符串排序
描述:
使用指向指针的指针对字符串排序,输出是按照字母顺序进行排序
2 思路
a. 熟悉指向指针的指针的使用
char*nums[]={"",""};
char**p;
p=nums;
熟悉 *p 指向的是 nums[0] 的首地址
b. 引用模块#include <string.h>
使用函数 int strcmp(const char *str1, const char *str2) 进行字符串的比较
该函数返回值如下:
如果返回值小于 0,则表示 str1 小于 str2。
如果返回值大于 0,则表示 str1 大于 str2。
如果返回值等于 0,则表示 str1 等于 str2。
3 代码
#include <stdio.h>
#include <string.h>
#define N 10
/**
函数:fun()
功能:使用指向指针的指针对字符串排序
描述:
使用指向指针的指针对字符串排序,输出是按照字母顺序进行排序
**/
voidsort(char**p) {
char*temp; // 排序交换时的临时变量
for(inti=0;i<N;++i) {
for(intj=i+1;j<N;++j) {
if(strcmp(*(p+i),*(p+j))>0) { // 使用strcmp进行字符串的比较
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;
}
}
}
}
intmain(intargc,charconst*argv[]) {
intn=5;
char**p;
char*nums[]={
"one","two","three","four","five","six","seven","eight","nine","ten"
};
p=nums; // 使用指向指针的指针指向字符串数组
printf("排序前的数组内容为:\n");
for(inti=0;i<N;++i) {
printf("%s ",*(p+i));
}
printf("\n");
sort(p);
printf("排序后的数组内容为:\n");
for(inti=0;i<N;++i) {
printf("%s ",*(p+i));
}
printf("\n");
}
示例结果:
$ gccex016.c-odemo
$ ./demo
排序前的数组内容为:
one two three four five six seven eight nine ten
排序后的数组内容为:
eight five four nine one seven six ten three two