• struct和typedef struct在c语言中的用法


    在c语言中,定义一个结构体要用typedef ,例如下面的示例代码,Stack sq;中的Stack就是struct Stack的别名。

    如果没有用到typedef,例如定义

    struct test1{
    int a;
    int b;
    int c;
    
    };

    test1 t;//声明变量

    下面语句就会报错

    struct.c:31:1: error: must use 'struct' tag to refer to type 'test1'

    test1 t;

    ^

    struct 

    1 error generated.

    声明变量时候就要用struct test1;这样就解决了

     

    如果这样定义的话

    typedef struct test3{
    int a;
    int b;
    int c;
    }test4;

    test3 d;
    test4 f;

    此时会报错

    struct.c:50:1: error: must use 'struct' tag to refer to type 'test3'

    test3 d;

    ^

    struct 

    1 error generated.

    所以要struct test3这样来声明变量d;

     

    分析一下:

    上面的test3是标识符,test4 是变量类型(相当于(int,char等))。

     

     我们可以用struct test3 d来定义变量d;为什么不能用test3 d来定义是错误的,因为test3相当于标识符,不是一个结构体,struc test3 合在一起才代表是一个结构类型。

    所以声明时候要test3时候要用struct test3 d;

     

    typedef其实是为这个结构体起了一个新的名字,test4;

    typedef struct test3 test4;

    test4 相当于struct test3;

    就是这么回事。

     

    #include<stdio.h>
    #include<stdlib.h>
    
    typedef struct Stack
    {
    char * elem;
    int top;
    int size;
    }Stack;
    
    struct test1{
    int a;
    int b;
    int c;
    
    };
    
    typedef struct{
    int a;
    int b;
    int c;
    
    }test2;
    int main(){
    
    printf("hello,vincent,
    ");
    Stack sq;
    sq.top = -1;
    sq.size=10;
    printf("top:%d,size:%d
    ",sq.top,sq.size);

    // 如果定义中没有typedef,就要用struct test1声明变量,否则报错:
    struct test1 t; t.a=1; t.b=2; t.c=3; printf("a:%d,b:%d,c:%d ",t.a,t.b,t.c); test2 e; e.a=4; e.b=5; e.c=6; printf("a:%d,b:%d,c:%d ",e.a,e.b,e.c); return 0; }
  • 相关阅读:
    SQL练习题32:请你创建一个actor_name表,并且将actor表中的所有first_name以及last_name导入该表.
    SQL练习题31:对于表actor批量插入如下数据,如果数据已经存在,请忽略(不支持使用replace操作)
    SQL练习题30:对于表actor批量插入如下数据(不能有2条insert语句哦!)
    npm run dev 报错:missing script:dev
    [转]vue中“:”、“.”、“@”的意义
    Vue踩坑记录
    Vue指令:v-clock解决页面闪烁问题
    npm-安装模块时出现rollbackFailedOptional
    js中[]、{}、()的区别
    IDEA离线安装插件
  • 原文地址:https://www.cnblogs.com/vincentqliu/p/typedef_struct.html
Copyright © 2020-2023  润新知