一、结构指针
结构指针即指向结构的指针,为什么要使用结构指针,主要有一下三点原因:
①就像指向数组的指针比数组不本身更容易操作(例如在一个排序问题中)一样,指向结构的指针通常比结构本身更容易操作
②在一些早期的C实现中,结构不能作为参数被传递给函数,但指向结构的指针可以
③许多奇妙的数据表示都使用了不包含指向其他结构的指针的结构
介绍一个运算符(“->”),称为“间接成员运算符”
这个运算符与指向结构或联合的指针一起使用,用来指明结构或联合的成员。假设ptstru是一个指向结构的指针,member是由该结构模板指定的一个变量的成员,那么:ptstru ->member 就表示指向的结构的成员
声明和初始化结构指针
声明很简单,例如:
struct student *p
结构指针的初始化
结构指针本质是指针,既然是指针,那么传入的就应该是地址,所以初始化应该如下:
p = &stu //stu以struct student 为模板
二、向函数传递结构信息的方法
②用结构体变量作实参
③用指向结构体变量(或数组)的指针作实参,将结构体变量(或数组)的地址传给形参
扫描二维码关注公众号,回复:
47361 查看本文章
接下来分别举例解释这几种方法:我们首先定义一个student结构体如下:
struct student{ int num; char name[20]; float score[3]; };
用结构体变量的成员作实参
这里写了一段代码来实现结构体的打印的功能,在print函数中传入了整个结构体变量
#include<stdio.h> struct student{ int num; char name[20]; float score[3]; };//定义结构体 struct student stu = { .num = 1702, .name = "Linden", .score = {99.7,99.2,98.9} };//结构体变量初始化 void print(struct student);//声明print函数 void main() { print(stu);//使用整个结构体变量作实参 }//主函数 void print(struct student stu) { printf("%d\n",stu.num); printf("%s\n",stu.name); printf("%.2f\n",stu.score[0]); printf("%.2f\n",stu.score[1]); printf("%.2f\n",stu.score[2]); }//print函数,注意struct student为变量类型,stu为形参
执行结果:
用指向结构体变量的指针作实参
对代码作如下修改:
#include<stdio.h> struct student{ int num; char name[20]; float score[3]; }; struct student stu = { .num = 1702, .name = "Linden", .score = {99.7,99.2,98.9} }; void print(struct student *);//函数声明,变量为指向struct student结构体类型的指针 void main() { print(&stu);//既然形参是一个指针,那传入的实参就应该是一个地址 } void print(struct student *p)//选用一个struct student类型的指针变量,并把它命名为p { printf("%d\n",p -> num);//有指针的情况下使用间接成员操作符,调用结构体里面的成员 printf("%s\n",p -> name); printf("%.2f\n",p -> score[0]); printf("%.2f\n",p -> score[1]); printf("%.2f\n",p -> score[2]); }
同样可以得到一样的运行结果: