结构体作为函数参数:
#include<stdio.h> #include<stdlib.h> #include<string.h> struct student { char name[10]; int age; }; void print_student(struct student s) { printf("name = %s,age = %d ",s.name,s.age); } void set_student(struct student *s,char *name,int age) { strcpy(s->name,name); s->age = age; } int main() { struct student st = {"tom",20}; set_student(&st,"mike",100); print_student(st); return 0; }
结构体作为函数参数时,实参传入地址,形参用指针接收。
运行结果;
exbot@ubuntu:~/wangqinghe/C/20190714$ ./struct2
name = mike,age = 100
如果函数参数的结构特别大,比如name[10000],会导致入栈速度变得很大,栈的内存变得很大,程序运行效率很低,所以一般来说不要把结构变量作为函数参数传递。
#include<stdio.h> #include<stdlib.h> #include<string.h> struct student { char name[10]; int age; }; void print_student(const struct student *s) { printf("name = %s,age = %d ",s->name,s->age); } void set_student(struct student *s,char *name,int age) { strcpy(s->name,name); s->age = age; } int main() { struct student st = {"tom",20}; set_student(&st,"mike",100); print_student(&st); return 0; }
运行结果:exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct2.c -o struct2
exbot@ubuntu:~/wangqinghe/C/20190714$ ./struct2
name = mike,age = 100
结论:在定义一个和结构体有关的函数时,尽量使用指针,而不是使用结构变量。因为使用指针,只需要传递地址大小的数据。