立即学习:https://edu.csdn.net/course/play/10534/378152?utm_source=blogtoedu
学习目标
函数指针参数和普通参数的区别。
什么情况下需要传指针。
指针参数
type fun(type *p, type *q);
// 调用
type *p = NULL;
type *q = NULL;
fun(p, q);
编程实例:定义一个函数,交换两个int变量的值。
#include <stdio.h>
// 值传递
void swap1(int a, int b) {
int t = a;
a = b;
b = t;
printf("swap >> a = %d, b = %d\n", a, b);
}
void swap2(int *pa, int *pb) {
int t = *pa;
*pa = *pb;
*pb = t;
}
int main(int argc, char* argv[]) {
int a = 10;
int b = 20;
printf("a = %d, b = %d\n", a, b);
swap1(a, b);
printf("a = %d, b = %d\n", a, b);
printf("---------------------\n");
printf("a = %d, b = %d\n", a, b);
swap2(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
什么时候传指针
需要修改地址上的值。
对象太大,节约空间,提高效率。
void fun1(int *p, char *q);
void fun2(Student* stud);
void fun3(int a[1024]);
编程实例:通过函数指针传递一个结构体,修改年龄,并返回旧的年龄。
#include <stdio.h>
typedef struct {
char name[32];
unsigned age;
} Student;
// sizeof(Student) 至少36个字节
// sizeof(Student *) 8个字节
unsigned modify_age(const Student *stud, const unsigned new_age) {
int old_age = stud->age;
stud->age = new_age;
return old_age;
}
int main(int argc, char* argv[]) {
Student stud = {"WangTeacher", 30};
printf("%s, %u\n", stud.name, stud.age);
unsigned old_age = modify_age(&stud, 100);
printf("%s, %u, old_age: %u\n", stud.name, stud.age, old_age);
return 0;
}