一维指针--用函数交换两个数的值
#include<stdio.h>
void fun1(int a,int b)
{
int temp;
if(a>b)
{
temp=a;
a=b;
b=temp;
}
}
void fun2(int *a,int *b)
{
int c;
if(*a>*b)
{
c=*a;
*a=*b;
*b=c;
}
}
int main()
{
int a=100,b=1;
fun1(a,b);
printf("a=%d,b=%d\n",a,b);
fun2(&a,&b);
printf("a=%d,b=%d\n",a,b);
return 0;
}
二维指针--交换两个指针的指向
#include<stdio.h>
void fun1(char **pa,char **pb)
{
char *p;
p=*pa;
*pa=*pb;
*pb=p;
}
int main()
{
char a='a',b='b';
char *pa=&a,*pb=&b;
printf("pa=%c,pb=%c\n",*pa,*pb);
fun1(&pa,&pb);
printf("pa=%c,pb=%c\n",*pa,*pb);
return 0;
}
字符串指针--指针指向字符串首地址
#include<stdio.h>
int main()
{
char *p="Hello World!";
char a[50]="This is a terrible world!";
printf("p=%p\n",p);
puts(p);
p=a;
puts(a);
printf("a=%p\n",a);
printf("p=%p\n",p);
return 0;
}
数组指针和指针数组
#include<stdio.h>
int main()
{
char *p[2]={"Hello ","world!"}; //p是一个数组,值为字符指针类型 。
char s[3]={'a','b','\0'};
char (*a)[3]=&s; //a是指针类型,指向char [3] 类型数组
puts(p[0]);
puts(p[1]);
puts(*a);
return 0;
}