近期在学习数据结构的单链表问题时,涉及到了结构体定义,结构体使用以及定义结构体指针变量的问题不是很清楚,现在对关于结构体指针变量的使用做下记录
方式一:
最基本方式:
struct 结构体类型名称 *指针变量名;
#include
#include
//定义一个结构体
typedef struct reader
{
//定义结构体的成员;
char name[32];
int age;
int number;
}
int main(){
//定义一个结构体变量
reader r1={"WWW",100,99};
//定义一个结构体指针变量
//结构体指针变量存放指定结构体变量的地址
reader *pr = &r1;
}
使用typedef以及struct关键字对结构体以及结构体指针进行定义
//定义结构体和结构体指针
typedef struct Student{
int number; //学号
int age; //年龄
bool gen; //性别,1女,0男
}Stu,*Stuzhizhen;
//用法
Stu stu1; //声明一个结构体Student变量stu1
Stuzhizhen p; //声明一个结构体Student指针变量p
//上述定义与下面等价
struct Student{
int number;
int age;
bool gen;
};
typedef struct Student Stu; //将结构体Student命名别名为Stu
typedef struct Student * Stuzhizhen; //将结构体Student指针类型命名别名为Stuzhizhen
//用法
struct Student stu1; //声明一个结构体Student变量stu1
struct Student * p; //声明一个结构体Student指针变量p;
结构体指针变量内存放的内容是一个结构体A的地址,故称为指针指向结构体A
一共有三种方式:
①结构体变量.成员名;
②结构体指针变量->成员名;
③(*结构体指针变量).成员名
“*” 对一级指针进行降级,将结构体指针转换为指针所指的结构体变量,
即(*结构体指针)就是“指针所指结构体便来给你”
#include
#include
//定义结构体
typedef struct Student
{
char name[32];
int age;
int number;
}Stu;
int main()
{
//声明一个结构体变量
Stu stu1={"WWW",100,99};
//在声明一个结构体变量
Stu stu2;
//声明一个结构体指针,用于存放一个结构体变量的地址
Stu *pr=&stu1;
(或者Stu *pr; pr=&stu1;)
//输出结构体变量stu1存放的内容,即sut1的成员
printf("stu1.name=%s\n",stu1.name);
printf("stu1.age=%d\n",stu1.age);
printf("stu1.number=%d\n",stu1.number);
//将指针变量pr所指向的变量设置给stu2,即赋值给r2
stu2=*pr;
printf("stu2.name=%s\n",stu2.name);
printf("stu1=2.age=%d\n",stu2.age);
printf("stu2.number=%d\n",stu2number);
//使用结构体指针操作
pr->age=168;
printf("stu1.age=%d\n",stu1.age);
(*pr).age=199;
printf("stu1.age=%d\n",stu1.age);
stu1.age=200;
printf("stu1.age=%d\n",stu1.age);
return 0;
}
则程序输出结果以此为:
WWW
100
99
WW
100
99
168
199
200
参考博文:
(3条消息) C语言结构体(5) 结构体指针变量_LC的专栏-CSDN博客_结构体指针变量https://blog.csdn.net/feng19870412/article/details/105201816