zoukankan      html  css  js  c++  java
  • 7.c语言程序设计---结构体、联合体、枚举类型

    结构体

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {    
        
        struct GamePlayerInfo //声明一个结构体,例如游戏中的一个结构体例子
        {
            char name[50]; //人物名字
            int HP; //HP 血量值
            int MP; //MP 魔法值
        };
    
        //使用
        struct GamePlayerInfo xiaoming = { "xiaoming",500,500 }; //初始化方式1
        struct GamePlayerInfo yaoguai = { .name = "yaoguai",.HP = 1000 }; //这样初始化也可以
        yaoguai.MP = 10000; //初始化方式3
        return 0;
    }
    //结构体里面还可以加结构体

    运行结果:

    typedef的使用
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {
    
        typedef struct GamePlayerInfo //typedef 给一个结构体起一个别名 Game
        {
            char name[50]; //人物名字
            int HP; //HP 血量值
            int MP; //MP 魔法值
        }Game;
    
        //使用
        Game xiaoming;
        xiaoming.MP = 10000; 
        return 0;
    }

    指针操作结构体

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {    
        
        struct GamePlayerInfo //声明一个结构体,例如游戏中的一个结构体例子
        {
            char name[50]; //人物名字
            int HP; //HP 血量值
            int MP; //MP 魔法值
        };
    
        //指针操作结构体
        struct GamePlayerInfo xiaoming = { "xiaoming",500,500 }; //实例化
        struct GamePlayerInfo * p; //声明一个指针p
        p = &xiaoming;  //p指向 xiaoming 这个结构,p就可以操作xiaoming 结构了
        printf("%s", p->name);
        printf("%s", (*p).name);
        return 0;  
    }

    运行结果:

    联合体

    联合体里面的成员都使用同一个地址,节省空间

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {    
        
        union Info
        {
            char name[50]; //人物名字
            int HP; //HP 血量值
            int MP; //MP 魔法值
        };
    
        union Info MyInfo;
        strcpy(MyInfo.name, "NPC"); //strcpy:字符串复制函数,把NPC复制到 MyInfo.name里面
        return 0;  
    }

    改第二个成员的值的时候,前面的成员的值就会乱码,所以同时只能使用一个成员

     修改第二个成员时(第一个成员name的值变为乱码):

    枚举类型

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    int main()
    {    
        
        enum color {red,blue,green}; //枚举类型 ,red=0,blue=1,green=2不断叠加
        printf("%d",blue);
        return 0;  
    }

  • 相关阅读:
    HDU 1058 Humble Numbers
    HDU 1160 FatMouse's Speed
    HDU 1087 Super Jumping! Jumping! Jumping!
    HDU 1003 Max Sum
    HDU 1297 Children’s Queue
    UVA1584环状序列 Circular Sequence
    UVA442 矩阵链乘 Matrix Chain Multiplication
    DjangoModels修改后出现You are trying to add a non-nullable field 'download' to book without a default; we can't do that (the database needs something to populate existing rows). Please select a fix:
    opencv做的简单播放器
    c++文件流输入输出
  • 原文地址:https://www.cnblogs.com/trevain/p/14466867.html
Copyright © 2011-2022 走看看