结构体指针变量 一提指针,那可是C语言的核心了,有多少学子曾拜倒在指针的脚下。单纯的说指针,其实并不难,但是与其它的结构搭配在一起,那可就愁死人了。比如说:数组一点都不难,但是与指针一起用,可就经常麻烦了。结构体也是一种结构,它与指针搭配怎么样呢? 一起来看一下吧! 1:结构体指针变量 和指针指向数组首地址一样,指针也可以指向结构体的起始地址。 形式形如: struct student *p; 上述语句定义了一个指针变量p,它指向任何一个属于struct student 类型的数据。通过指针去访问所指结构体变量的某个成员时,有两种方法: (*p).score 或者 p->score(这是一种常用的方式。->是指向运算符) 比如: 访问的时候:(*p).num=11031,或者 p->num=11031。 2.程序实例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include <stdio.h> /*定义结构体*/ struct student { int num; char name[20]; char sex; int age; float score; }; /*初始化一个结构体实例*/ struct student stu[3]={ {11302, "Wang" , 'F' ,20,486.69}, {11303, "Zhao" , 'F' ,25,466.59}, {11304, "Xue" , 'M' ,26,483.59} }; main() { /*初始化一个student1的实例*/ struct student student1={11305, "Li" , 'F' ,19,59.59}; struct student *p,*q; //定义struct student类型的指针 int i; p=&student1; //将student 1的结构体的首地址赋给p,也就是p指向了student 1的首地址 /*输出:可以看到,访问结构体的成员,有三种方法*/ printf ( "%s,%c,%f\n" ,student1.name,(*p).sex,p->score); q=stu; //将数组stu的首地址赋给q; /*for循环输出数组中的成员*/ for (i=0;i<3;i++,q++) { printf ( "%s,%c,%f\n" ,q->name,(*q).sex,stu[i].score); } } 3.指针符号(->) P->num P指向的结构体中的成员 P->num++ 先得到p所指向的结构体成员num,然后使该num的值加1 ++p->num 先p所指向成员num的值加1,然后引用这个新的值 (p++)->num 先引用p->num的值,用完之后再使p加1 (++p)->num 先p加1,然后引用p->num的值 4.结构体变量和结构体指针变量做函数参数 结构体变量以及结构体指针变量均可以像int类型那样作为函数的参数。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 #include <stdio.h> /*定义结构体*/ struct student { int num; char name[20]; char sex; int age; float score; }; /*初始化一个结构体实例*/ struct student stu[3]={ {11302, "Wang" , 'F' ,20,486.69}, {11303, "Zhao" , 'F' ,25,466.59}, {11304, "Xue" , 'M' ,18,483.59} }; /*输出函数,结构体变量s做为函数参数*/ void print( struct student s) { printf ( "%s,%d,%f\n" ,s.name,s.age,s.score); } /*增加成绩的函数,结构体指针q作为函数参数*/ void add( struct student *q) { if (q->age<=19) q->score=q->score+10; } main() { struct student *p; int i; for (i=0;i<3;i++) { print(stu[i]); //stu[i]作为形参 } for (i=0,p=stu;i<3;i++,p++) { add(p); //指向stu的指针变量p作为形参 } printf ( "\n" ); for (i=0,p=stu;i<3;i++,p++) { print(*p); //*p作为形参,相当于stu[i] } } 上述程序注意的是:调用函数print和add都是void无返回值类型的函数,如果是有返回值的,它的类型应该是struct student类型,也就是说应该是 语言 1 2 3 4 5 6 struct student add(struct student *q) { if (q->age<= 19 ) q->score=q->score+ 10 ; return *q } 转自 http://zhaoyuqiang.blog.51cto.com/6328846/1292014