主函數中輸入10個等長的字串,用另一函數對他們排序,然後再主函數輸出這10個一排好序的字串!

來源:互聯網
上載者:User

//用指標數組處理

#include<stdio.h>
#include<string.h>
int main()
{
 void sort(char *[]);
 int i;
 char str[10][6], *p[10];
 printf("please input 10 string:/n");
 for(i=0;i<10;i++)//首先將10個str的首地址賦值給10個p[i];
  p[i]=str[i];//將第i個字串的首地址賦予指標數組p的第i個元素;
 for(i=0;i<10;i++)
  scanf("%s",p[i]);//scanf輸入到&p[i]
 sort(p);
 printf("the output 10 string:/n");
 for(i=0;i<10;i++)
  printf("%s/n",p[i]);//輸出到p[i];
}
void sort(char *s[])
{
 char *temp;
 int i,j;
 for(i=0;i<9;i++)
  for(j=0;j<9-i;j++)
   if(strcmp(*(s+j),*(s+j+1))>0)
   {
    temp=*(s+j);//*(s+j)指向數組指標,我想應該是字串的首地址;所以可以直接賦值給temp指標;
    *(s+j)=*(s+j+1);
    *(s+j+1)=temp;
   }
}

//字元型二維數組
#include<stdio.h>
#include<string.h>
int main()
{
 void sort( char s[][6]);
 char str[10][6];
 int i;
 printf("please input string:/n");
 for(i=0;i<10;i++)
  scanf("%s",&str[i]);//str是指向由6個元素組成的一維數組的指標
 sort(str);//str是指向由6個元素組成的一維數組的指標
 printf("please output string:/n");
 for(i=0;i<10;i++)
 {
  printf("%s",str[i]);//str是指向由6個元素組成的一維數組的指標
  printf("/n");
 }
 return 0;
}
void sort(char s[10][6])//形參s是指向由6個元素組成的一維數組的指標
{
 char *p,temp[10];
 int i,j;
 p=temp;
 for(i=0;i<10;i++)
  for(j=0;j<10-i;j++)
   if(strcmp(s[j],s[j+1])>0)//格式錯誤不是strcmp(s[j]>s[j+1]);比較之後
   {
    strcpy(p,s[j]);
    strcpy(s[j],s[j+1]);
    strcpy(s[j+1],p);
   }
}

 

用指向一維數組的指標做函數參數

#include<stdio.h>
#include<string.h>
int main()
{
 void sort(char (*s)[6]);//一維數組的指標做函數參數
 int i;
 char str[10][6];
 char (*p)[6];//定義一維數組的指標做函數參數
 printf("please input string:/n");
 for(i=0;i<10;i++)
  scanf("%s",&str[i]);
 p=str;//將str一維數組指標,賦值給p;
    sort(p);
 printf("the output sequence :/n");
 for(i=0;i<10;i++)
  printf("%s/n",str[i]);
 return 0;
}
void sort(char (*s)[6])//s指向一維數組的指標做函數參數;
{
 int i,j;
 char temp[6], *t;
 t=temp;
    for(i=0;i<9;i++)//i應該小於9;如果小於10,那麼就比較了9+1次;按照冒泡法則,
  for(j=0;j<9-i;j++)//第一次比較需要9次就是i=0到i=8共九次;第二次需要比較8次;依次類推;
   if(strcmp(s[j],s[j+1])>0)
   {
    strcpy(t,s[j]);
    strcpy(s[j],s[j+1]);
    strcpy(s[j+1],t);
   }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.