文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C程序习题-用指针的指针对字符串进行排序[10.20]

C程序习题-用指针的指针对字符串进行排序[10.20]

时间:2010-08-24  来源:chengxiaopeng

    用指向指针的指针的方法对5个字符串排序输出。     使用指向指针的指针,我们需要注意,当我们需要获取字符串的值,需要使用*p,如果需要获取非字符串的的值,需要使用**p,排序我们可以使用选择排序法。代码如下:

#include <stdio.h>

void print(char **,int);
void sort(char **,int);
int mystrcmp(char *,char *);
int main(int argc, char *argv[])
{
    char ch[5][20],*p_ch[5],**p;
    int i;
    for (i = 0; i < 5; i++)
    {
        p_ch[i] = ch[i];
    }
    p = p_ch;
    
    printf("please input 5 string(5 line):\n");
    for(i = 0; i < 5; i++)
    {
          scanf("%s",*p++);
    }
    printf("the source is :\n");
    p = p_ch;
    print(p,5);
    printf("the sort result:\n");
    p = p_ch;
    sort(p,5);
    p = p_ch;
    print(p,5);
    
    system("pause");
    return 0;
}

void print(char **p,int n)
{
     int i;
     for (i = 0; i < n; i++)
     {
         printf("%s\n",*p++);
     }
}

void sort(char **p,int n)
{
     int i,j,k;
     char *temp;
     for (i = 0; i < n - 1; i++)
     {
         k = i;
         for (j = i + 1; j < n; j++)
         {
             if (mystrcmp(*(p + k),*(p + j)) > 0)
             {
                k = j;
             }
         }
         if (k != i)
         {
            temp = *(p + i);
            *(p + i) = *(p + k);
            *(p + k)= temp;
         }
     }
}

int mystrcmp(char *ch1,char *ch2)
{
    int result = 0;
    while (*ch1 && *ch2)
    {
          if (*ch1 == *ch2)
          {
             ch1++;
             ch2++;
             continue;
          }
          else
          {
              result = *ch1 - *ch2;
              break;
          }
    }
    return result;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载