关于C语言指针数组的几个实例

来源:互联网 发布:淘宝客佣金怎么算的 编辑:程序博客网 时间:2024/06/06 03:59

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

#include<stdio.h>
#include<string.h>
int Sort(char **p)
{
int i,j;char *temp;
for(i=0;i<4;i++)
for(j=0;j<4-i;j++)
if(strcmp(*(p+j),*(p+j+1))>0)
{
temp=*(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}
return 1;
}


void main( )
{
char *str[5],a[5][10],**p;int i;p=str;
printf("Please input the five strings!\n");
    for(i=0;i<5;i++)
{
scanf("%s",&a[i]);
str[i]=a[i];
}
Sort(p);
for(i=0;i<5;i++)
printf("%s ",*(p+i));
printf("\n");
}

2.用指向指针的指针的方法对n个整数排序并输出。要求将排序的方法写成一个函数。n个整数在主函数中输入,最后在主函数中输出。

#include<stdio.h>
int Sort(int **p,int n)
{
int i,j;int temp;
for(i=0;i<n;i++)
for(j=0;j<n-1-i;j++)
if(**(p+j)>**(p+j+1))
{
temp=**(p+j);
**(p+j)=**(p+j+1);
**(p+j+1)=temp;
}
return 1;
}
void main( )
{
int *num[100],a[100],**p;p=num;int i,n;
printf("Please input the account of the numbers!\n");
scanf("%d",&n);
printf("Please input the numbers!\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
num[i]=&a[i];
}
Sort(p,n);
for(i=0;i<n;i++)
printf("%d ",**(p+i));
}


3.在主函数中输入10个等长的字符串。用另一个函数对他们进行排序。然后在主函数输出这10个已排好序的字符串

#include<stdio.h>
#include<string.h>
int main( )
{
void sort(char *[ ]);
char a[10][6],*str[10];
int i;
printf("Please input the ten strings:\n");
     for(i=0;i<10;i++)
    str[i]=a[i];
    for(i=0;i<10;i++)
    scanf("%s",str[i]);
sort(str);
for(i=0;i<10;i++)
printf("%s\n",str[i]);


}


void sort(char *str[ ])
{
 char *temp;
 int i,j;
 for(i=0;i<9;i++)
  for(j=0;j<9-i;j++)
   if(strcmp(*(str+j),*(str+j+1))>0)
   {
    temp=*(str+j);
    *(str+j)=*(str+j+1);
    *(str+j+1)=temp;
   }
}


0 0