1.用指针交换两个变量的值
#include <bits/stdc++.h>
using namespace std;
void swap(int *p,int *q)
{
int t;
t=*q;
*q=*p;
*p=t;
/*错误做法:这样写不起作用,两个数是没有被交换的。
int *t;
t=q;
q=p;
p=t;
*/
}
int main()
{
int a,b;
cin>>a>>b;
swap(&a,&b);
cout<<a<<" "<<b;
return 0;
}
2.二维数组的行指针
int a[2][3];
int (*p)[3];//注意[n],n一定要与定义的数组列数相同
p=a;
//输入输出二维数组
#include <bits/stdc++.h>
using namespace std;
void f(int (*p)[4])
{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<4;j++)
scanf("%d",*(p+i)+j);//也可以用 &p[i][j]
for(i=0;i<2;i++)
for(j=0;j<4;j++)
{
if(j!=3)
cout<<*(*(p+i)+j)<<" ";//也可以用 p[i][j]
else
cout<<*(*(p+i)+j)<<endl;
}
}
int main()
{
int a[2][4];
f(a);
return 0;
}
输入:
1 2 3 4
5 6 7 8
输出:
1 2 3 4
5 6 7 8
3.二维数组的列指针
int a[2][3];
int *p;
p=*a;
//输入输出二维数组
#include <bits/stdc++.h>
using namespace std;
void f(int *p)
{
int i,j;
for(i=0;i<2;i++)
for(j=0;j<4;j++)
scanf("%d",p+i*4+j);//也可以用 &p[i*4+j] (注意i*n,n必须是定义的数组的列数)
for(i=0;i<2;i++)
for(j=0;j<4;j++)
{
if(j!=3)
cout<<*(p+i*4+j)<<" ";//也可以用 p[i*4+j]
else
cout<<*(p+i*4+j)<<endl;
}
}
int main()
{
int a[2][4];
f(*a);
return 0;
}
输入:
1 2 3 4
5 6 7 8
输出:
1 2 3 4
5 6 7 8
4.指针数组
int *p[5];
#include<bits/stdc++.h>
using namespace std;
void psort(char *a[5])
{
char *p;
for(int i=0;i<5;i++)
for(int j=i+1;j<5;j++)
{
if(strcmp(a[i],a[j])>0)
{
p=a[i];
a[i]=a[j];
a[j]=p;
}
}
}
int main()
{
char *p[5];
for(int i=0;i<5;i++)
{
p[i]=(char *)malloc(sizeof(char)*10);
cin>>p[i];
}
psort(p);
for(int i=0;i<5;i++)
cout<<p[i]<<endl;
return 0;
}
输入:
China Australia Singapore Canada Zambia
输出:
Australia
Canada
China
Singapore
Zambia