指针的理解:内存是我们程序运行时候数据暂存的地方,内存是有大小的,我们可以把内存想象成一个连在一起的房间,每个房间都有自己的房间号,这个房间号就是我们内存中每个字节的“地址“,我们可以根据这个房间号来找到我们所住的房间,我们也可以根据这个地址来找到我们所使用的字节。内存是宝贵的,所以我们要灵活的使用指针。
例子1: #include<stdio.h>
int swap(int x,int y)
{
int c;
c=x;
x=y;
y=c;
return 0;
}
/*int swap2(int *x,int *y)
{
int d;
d=*x;
*x=*y;
*y=d;
}*/
int main()
{
int a=1;
int b=2;
swap(a,b);
// swap2(&a,&b);
printf("%d,%d\n",a,b);
return 0;
} 打印结果: #include<stdio.h>
int swap(int x,int y)
{
int c;
c=x;
x=y;
y=c;
return 0;
}
/*int swap2(int *x,int *y)
{
int d;
d=*x;
*x=*y;
*y=d;
}*/
int main()
{
int a=1;
int b=2;
swap(a,b);
// swap2(&a,&b);
printf("%d,%d\n",a,b);
return 0;
} #include<stdio.h>
int swap(int x,int y)
{
int c;
c=x;
x=y;
y=c;
return 0;
}
/*int swap2(int *x,int *y)
{
int d;
d=*x;
*x=*y;
*y=d;
}*/
int main()
{
int a=1;
int b=2;
swap(a,b);
// swap2(&a,&b);
printf("%d,%d\n",a,b);
return 0;
}
#include<stdio.h>
int swap(int x,int y)
{
int c;
c=x;
x=y;
y=c;
return 0;
}
/*int swap2(int *x,int *y)
{
int d;
d=*x;
*x=*y;
*y=d;
}*/
int main()
{
int a=1;
int b=2;
swap(a,b);
// swap2(&a,&b);
printf("%d,%d\n",a,b);
return 0;
}
liuzj@ET302Buildver:~/zhanghong/make$ gcc swap.c
liuzj@ET302Buildver:~/zhanghong/make$ ./a.out
1,2
liuzj@ET302Buildver:~/zhanghong/make$ 解析:调用了swap函数,为什么a和b没有交换呢?我们传的a和b是形参,交换的是a和b的复制品,但是a和b并没有交换,就比如房间1里放了个a,房间2里放了个b,你把a和b的复制品交到另一个人手上,那个人把a和b的复制品进行交换,a和b的本身当然没有交换啊,所以只有传递地址才是传递这个参数的本身,所以地址才是唯一的。 例2:
#include<stdio.h>
/*int swap(int x,int y)
{
int c;
c=x;
x=y;
y=c;
return 0;
}*/
int swap2(int *x,int *y)
{
int d;
d=*x;
*x=*y;
*y=d;
}
int main()
{
int a=1;
int b=2;
// swap(a,b);
swap2(&a,&b);
printf("%d,%d\n",a,b);
return 0;
}
结果: liuzj@ET302Buildver:~/zhanghong/make$ vim swap.c
liuzj@ET302Buildver:~/zhanghong/make$ gcc swap.c
liuzj@ET302Buildver:~/zhanghong/make$ ./a.out
2,1
liuzj@ET302Buildver:~/zhanghong/make$ 解析:这里的a和b就交换了,这里传的是地址,把1号房间的东西放到房间2里面,把房间2的东西放到房间1里面!