C语言-结构体指针变量的使用

近期在学习数据结构的单链表问题时,涉及到了结构体定义,结构体使用以及定义结构体指针变量的问题不是很清楚,现在对关于结构体指针变量的使用做下记录

结构体指针变量的定义方式:

方式一:

最基本方式:

struct   结构体类型名称  *指针变量名;

#include<stdlib.h>
#include<stdio.h>


//定义一个结构体
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<stdlib.h>
#include<stdio.h>

//定义结构体
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

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值