例81:C語言實作用指向指針的指針的方法對5個字元串排序并輸出。 解題思路:讀者看着道題的時候,首先要知道什麼時指針,指向指針的指針應該怎麼用,一般在開發中不這樣用,讀者要看明白,這個很鍛煉思維的。C語言源代碼示範:#include<stdio.h>//頭檔案
#include<string.h>
#define LINEMAX 20 //定義字元串的最大長度
int main()
{
void sort(char **point);//函數聲明
int i;//定義整型變量
char **point,*pstr[5],str[5][LINEMAX];//定義變量
for(i=0;i<5;i++)
{
pstr[i]=str[i]; //将第i個字元串的首位址賦予指針數組pstr的第i個元素
}
printf("輸入五個字元串:\n");//提示語句
scanf("%s",pstr[i]);
point=pstr;
sort(point);//調用sort函數
printf("————————————\n");//提示語句
printf("輸出排序後的結果:\n");//提示語句
printf("%s\n",pstr[i]);
return 0;//主函數傳回值為0
}
void sort(char **point)//冒泡排序算法實作
{
int i,j;//定義整型變量
char *temp;//定義字元指針變量
for(j=i+1;j<5;j++)
{
if(strcmp(*(point+i),*(point+j))>0)//比較後交換字元串位址
{
temp=*(point+i);
*(point+i)=*(point+j);
*(point+j)=temp;
}
}
}
}編譯運作結果:輸入五個字元串:
China
American
Japan
Back
Different
————————————
輸出排序後的結果:
--------------------------------
Process exited after 2.574 seconds with return value 0
請按任意鍵繼續. . .