【C语言】指针到底有什么用?

很多初学者(包括我),学习指针的时候总有这样一个疑问:指针到底有什么用?只是多了一种访问变量的方法而已,有这么重要么?

举个例子:通过函数交换两个整型变量的值

初学者一般都会这么写

#include <stdio.h>
void Swap(int a, int b) {
	int temp = a;
	a = b;
	b = temp;
}
int main(void) {
	int a=1, b=2;
	Swap(a, b);
	printf("%d, %d\n", a, b);
	return 0;
}

输出结果

1, 2

交换失败。
为啥呢?
不知道的同学可以补习一下变量的作用域相关知识。

使用指针交换

#include <stdio.h>
void Swap(int* pa, int* pb) {
	int temp = *pa;
	*pa = *pb;
	*pb = temp;
}
int main(void) {
	int a=1, b=2;
	Swap(&a, &b);
	printf("%d, %d\n", a, b);
	return 0;
}

输出结果

2, 1

交换成功。
为啥呢?
因为 Swap() 函数传入的是两个指针,有了指针,就可以冲出 Swap() 函数,拿着指针找变量了。

再举个例子: scanf() 函数

为啥 scanf() 函数传入的是指针而不是变量本身呢?

我们模拟一下

#include <stdio.h>
void Scanf(int a) {
	a = 1;  //假设获取到了1
}
int main(void) {
	int a;
	Scanf(a);
	printf("%d\n", a);
	return 0;
}

输出结果(不同的编译器下可能不同)

4198575

没有成功赋值。

使用指针赋值

#include <stdio.h>
void Scanf(int* pa) {
	*pa = 1;  //假设获取到了1
}
int main(void) {
	int a;
	Scanf(&a);
	printf("%d\n", a);
	return 0;
}

输出结果

1

成功赋值。

所以,指针是连接主调函数和被调函数的桥梁。

再举个例子:将结构体作为函数参数

有如下代码

#include <stdio.h>
typedef struct Student {
	char *name;
	int age;
	int score;
} Student;
void say(Student stu) {
	printf("我是%s,年龄%d岁,成绩是%d\n", stu.name, stu.age, stu.score);
}
int main(void) {
	Student stu;
	stu.name = "小明";
	stu.age = 10;
	stu.score = 90;
	printf("sizeof(stu)=%d\n", 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\n", stu->name, stu->age, stu->score);
}
int main(void) {
	Student stu;
	stu.name = "小明";
	stu.age = 10;
	stu.score = 90;
	printf("sizeof(stu)=%d, sizeof(pstu)=%d\n", sizeof(stu), sizeof(&stu));
	say(&stu);
	return 0;
}

输出结果

sizeof(stu)=12, sizeof(pstu)=4
我是小明,年龄10岁,成绩是90

可见,使用结构体指针的空间开销比直接使用结构体变量要小。

所以,使用指针可以使时间和空间开销更小。

猜你喜欢

转载自www.cnblogs.com/HuZhixiang/p/12932494.html
今日推荐