大家一致认为C/C++中最难的就是指针操作,偏偏指针操作是C/C++的精髓所在。所以要用C/C++就必须越过这座大山。
互换两个数值可谓是C指针操作的经典题目,下面我想对这道题目做下讲解。
如果不用调用函数要实现呼唤就很简单:
int a = 8;
int b = 9;
int t = 0;
t = a, a = b, b = t; 有这行代码就行了。
下面有调用函数的方法来是实现,大家刚写的时候都容易犯下面的程序的错误,不过能犯下面的错误说明你也懂一点了,具体代码如下:
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int *t = 0;
t = a;
a = b;
b = t;
return;
}
int main(void)
{
int a = 9;
int b = 8;
int t = 0;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
上述这段代码还是不能实现互换两个值,上述程序试图变换a, b的地址值来变换他们的值。实际上不可能的,他们地址是开始使用它的时候就进行了分配,你是改变不了他们的地址。稍微修改一下上面的代码就可以实现了:
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int t = 0;
t = *a;
*a = *b;
*b = t;
return;
}
int main(void)
{
int a = 9;
int b = 8;
int t = 0;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
上面函数的基本大意是:把a, b的地址传给调用函数,被调函数将得到的地址所指向的值就行了互换。