关于typedef struct和struct对比

  • 为什么要提出typedef的用法,因为相对于struct 结构体使用起来更方便。下面就是他们之间的对比:

  1. struct结构体
#include"stdio.h"
 
 
 struct Student 
 {
  int sid;
  char name [100];
  char sex;   
 }
 
 int main(){
     struct Student st; //定义结构体变量
     struct Student * ps=&st;
     return 0;
 }
  

      2.如果是typedef

typedef int   A   ; //为int 再重新多取一个名字,A等价于int

typedef struct Student    //为struct Student 的数据类型再重新多取了一个名字,
                            ST等价于 struct Student
{
    int sid;
    char name [100];
    char sex;  
}  ST;               

int main(){
    A a=10;          //等价于 int a=10;
    struct Student st;  //用了struct Student方法的定义
    struct Student * ps=&st;
    
         
    st.sid=200;
    return 0;
}

/************************
int main(){
    A a=10;   //等价于int a=10;
    ST st;     //用了typedef方法的定义, ST等价于 struct Student    
    ST * ps=&st;
    st.sid=200;
    return 0;
}

*********************************/
以上两种表示方法都可以!
#include "stdio.h"
typedef struct Student    //为struct Student * 的数据类型再重新多取了一个名字,
                            PST等价于 struct Student * 
                            ST等价于  struct Student
{
    int sid;
    char name [100];
    char sex;  
}  *  PST,ST;    
 
int  main(void){
    ST st1;           //等价于 struct Student st1;
    struct Student st;  
    PST ps=&st;   //PST等价于 struct Student *,
             所以初始化是初始化struct Student *变量ps,即ps是指向结构体的指针
    ps->sid=99; //(*st).sid=99;
    return 0;
      
}

由上面可知,定义结构体变量时,不需要每次都写 struct Student  st,可用typedef取得名字来定义结构体变量ST st。

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值