C语言使用指针数组实现对输入的三个字符串按由小到大的顺序输出

定义指针数组比较容易处理这个问题,

第一种写法:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>//引入sin x,cos x,e^x的库
//使用指向函数的指针变量来复用一个通用函数
int main()
{
    char str1[10],str2[10],str3[10];
    char *p[3];
    int i;
    printf("请输入三个字符串\n");
    gets(str1);
    gets(str2);
    gets(str3);
    //指针开始指向
    p[0]=str1;
    p[1]=str2;
    p[2]=str3;
   //比较大小,交换地址,同时进行
   swap(p);
   //打印输出
   for (i=0;i<3;i++)
   {
       printf("%s\n",p[i]);
   }
    //使用指针数组存放指针数
}
swap(char *p[])
{
   //
   char *temp;
   int i,j;
   for (i=0;i<3;i++)
   {
       //printf("%s\n",p[i]);
       for (j=i+1;j<3;j++)
       {
           if (strcmp(p[i],p[j])>0)//交换
           {
               temp=p[i];
               p[i]=p[j];
               p[j]=temp;
           }
       }
   }

}

第二种使用strcpy来交换两者字符串的内容;

易错点:博主曾试图交换指针变量改变指针的指向使得值改变,然而C语言函数传值为单向转递,函数块一出指针变量没有改变指向。特此记录一下。

猜你喜欢

转载自blog.csdn.net/Warkey1998/article/details/82873788