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

//C程序设计第四版(谭浩强)
//章节:第八章 善于利用指针 
//题号:8.20
//题目:用指向指针的指针的方法对5个字符串排序并输出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *p[],int n)	//对字符串排序的函数 
{
	char *temp;
	int i,j,k;
	for(i=0;i<n-1;i++)
	{
		k=i;
		for(j=i+1;j<n;j++)
			if(strcmp(p[k],p[j])>0)
				k=j;
		if(k!=i)
		{
			temp=p[i];
			p[i]=p[k];
			p[k]=temp;
		}
	}
}
int main()
{
	int i;
	char *p[5];
	printf("input 5 strings:\n");
	for(i=0;i<5;i++)
	{
		p[i]=(char *)malloc(sizeof(char)*40);	//注意:输入时需分配空间 
		gets(p[i]);			//40为每个字符串的长度,可任意修改 
	}
	sort(p,5);
	printf("after sort:\n");
	for(i=0;i<5;i++)
		printf("%s\n",p[i]);
	return 0; 
 } 

猜你喜欢

转载自blog.csdn.net/weixin_44589540/article/details/86668531