关于typedef和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 st2;       //用了typedef方法的定义, ST等价于 struct Student
    st2.sid=200;
    return 0;
}

/************************
int main(){
    A a=10;   //等价于int a=10;
    ST st;
    ST * ps=st;
    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; //(*ps).sid=99;
    return 0;
      
}

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

skr
发布了1 篇原创文章 · 获赞 1 · 访问量 65

猜你喜欢

转载自blog.csdn.net/weixin_42760452/article/details/104643775