结构体变量与指针

来源:互联网 发布:羽绒服清洗剂 知乎 编辑:程序博客网 时间:2024/04/28 18:32
指向结构体变量的指针变量定义的一般形式是:
struct 结构体名 *结构体指针变量名;
例如:
struct student *p;
struct student stu1;
p = &stu1; /* p指向结构体变量stu1 */
示例:

#include <stdio.h>
#include <string.h>

struct student
{
int num;
char name[10];
char subject[20];
};


void main (void)
{
struct student student1, *p;
student1.num = 13;
p = &student1;
strcpy((*p).name, "米粒");

/*易犯错误:

(*p).name = "米粒";是错误的,字符串只能在数组定义的时候赋值,定义后不能再进行赋值操作; */

strcpy(p->subject, "音乐");

printf("学号:%d\n姓名:%s\n专业:音乐\n", (*p).num, student1.name, p->subject);
}
/*VC++6.0执行结果:
-------------------
学号:13
姓名:米粒
专业:音乐
-------------------
*/

【程序分析】
首先定义一个结构体类型struct student。在主函数main()中定义一个struct student类型的变量student1和一个指向struct student类型的指针变量p。然后给student1的各成员赋值,并将student1的起始地址赋给指针变量p,即p指向student1。(*p)表示p指向的结构体变量student1,(*p).num表示p指向的student1的成员num。注意:运算符“.”的优先级高于“*”,所以(*p)的括号不能省略。
当一个指针变量指向某个具体的结构体变量时,就可以利用该指针变量来间接访问结构体变量的各个成员。常用的方式有两种:
1. (*指针变量).成员。
2. 指针变量->成员。(->称为指向运算符)
上例中,(*p).num等价于p->num,表示p指向的结构体变量的成员num。
0 0
原创粉丝点击