指针到底有什么用?只是多了一种访问变量的方法而已,有这么重要吗?
1. 通过函数修改形参的值(例子:交换两个形参的值)
错误写法
#include <stdio.h>
void MySwap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main(void) {
int a=1, b=2;
MySwap(a, b);
printf("%d, %d
", a, b);
return 0;
}
输出结果
1, 2
交换失败。因为MySwap()
函数中的参数是局部变量,和main()
函数中的变量没有任何关系。
正确写法
#include <stdio.h>
void MySwap(int* pa, int* pb) {
int temp = *pa;
*pa = *pb;
*pb = temp;
}
int main(void) {
int a=1, b=2;
MySwap(&a, &b);
printf("%d, %d
", a, b);
return 0;
}
输出结果
2, 1
交换成功。因为MySwap()
函数的参数是指针,可以通过指针直接修改内存上的数据。
所以,函数中将指针作为参数可以直接修改主调函数中变量的值。
2. 将结构体作为函数参数(例子:输出学生信息)
不合适的写法
#include <stdio.h>
typedef struct Student {
char *name;
int age;
int score;
} Student;
void Say(Student stu) {
printf("我是%s,年龄是%d,成绩是%d
", stu.name, stu.age, stu.score);
}
int main(void) {
Student stu;
stu.name = "小明";
stu.age = 10;
stu.score = 90;
printf("sizeof(stu)=%d
", sizeof(stu));
Say(stu);
return 0;
}
输出结果
sizeof(stu)=12
我是小明,年龄是10,成绩是90
stu
结构体变量占用了12个字节,在调用函数时,需要原封不动地将12个字节传递给形参。如果结构体成员很多,传送的时间和空间开销就会很大,影响运行效率。
正确写法
#include <stdio.h>
typedef struct Student {
char *name;
int age;
int score;
} Student;
void Say(Student *stu) {
printf("我是%s,年龄是%d,成绩是%d
", stu->name, stu->age, stu->score);
}
int main(void) {
Student stu;
stu.name = "小明";
stu.age = 10;
stu.score = 90;
printf("sizeof(&stu)=%d
", sizeof(&stu));
Say(&stu);
return 0;
}
输出结果
sizeof(&stu)=12
我是小明,年龄是10,成绩是90
可见,使用结构体指针的空间开销比直接使用结构体变量要少,当结构体的成员很多时,还可以减少时间开销,提高运行效率。
所以,使用指针可以减少空间和时间开销。