zoukankan      html  css  js  c++  java
  • step2 . day5 C语言中的结构体和枚举

    最近几天交叉的学习C和Linux,知识梳理的不是很仔细,有很多还没有搞明白的问题,所有耽误了几天更新笔记,也是在细嚼慢咽中,做了一个规划表,现阶段先把C后面的知识学好,然后再梳理Linux系统相关知识,争取在本月做完汇总,把step1和step2的目标达成。

    1. 枚举类型及使用

    #include<stdio.h>

    enum calc_t{
    add,
    sub,
    mul,
    div,
    mod
    };

    int mycalc(int a,int b,enum calc_t c)
    {
    switch(c){
    case add:return a+b;break;
    case sub:return a-b;break;
    case mul:return a*b;break;
    case div:return a/b;break;
    case mod:return a%b;break;
    default:
    printf("error! ");break;

    }

    }
    int main(int argc, const char *argv[])
    {
    printf("a + b =%d ",mycalc(3,4,add));
    printf("a - b =%d ",mycalc(3,4,sub));
    printf("a * b =%d ",mycalc(3,4,mul));
    printf("a / b =%d ",mycalc(3,4,div));
    printf("a %% b =%d ",mycalc(3,4,mod));
    return 0;
    }

    注意,枚举的数据类型测试是4个字节,不知道为啥,还在研究中

    2. 结构体的声明和赋值:

    #include<stdio.h>
    struct student{
    int id;
    int score;
    }stu[3] = {1,2,3,4,5,6};
    int main(int argc, const char *argv[])
    {
    struct student stu1[2] = {{7,8},{9,10}};
    struct student stu2[2] = {
    [0] = {11,12},
    [1] = {13,14}
    };
    struct student stu3[2] = {
    {.id = 15,.score = 16},
    {17,18}
    };
    struct student stu4[2];
    stu4[0].id = 19;
    stu4[1].score =20;
    return 0;
    }

    3.结构体的使用


    #include<stdio.h>
    #include<string.h>

    struct student{
    char name[32];
    int age;
    int id;
    int score;
    };

    void stu_info_input(struct student *stu){
    // char nametem[32];
    printf("******************************** ");
    printf("please input student's name:");
    scanf("%s",stu->name);
    // strcpy(stu->name,nametem);
    printf("please input student's age:");
    scanf("%d",&stu->age);
    printf("please input student's id:");
    scanf("%d",&stu->id);
    printf("please input student's score:");
    scanf("%d",&stu->score);
    }

    void stu_info_output(struct student *stu){

    printf("Name Age ID Score ");
    printf("%s %d %d %d ",stu->name,stu->age,stu->id,stu->score);
    }

    int main(int argc, const char *argv[])
    {
    struct student stu,*s;
    s = &stu;

    stu_info_input(s);
    stu_info_output(s);
    return 0;
    }

    4.结构体的大小(sizeof(struct name)),遵从数据对齐方式,是最大数据长度的整数倍,

    char占用一个字节   

    short占用两个,内存需要从0,2,4,6,8,开始存储,

    int 占4个字节  存储需从0,4,8等被整除的位置开始存储

    double为特殊,占8个字节,则是从4开始,同int存储位置。内存补齐遵守原则要牢记

  • 相关阅读:
    web 移动端 适配
    meta
    meta设置
    时间
    CentOS下配置nginx conf/koi-win为同一文件的各类错误
    CentOS7 配置LAMP
    centos 进度条卡死
    LeetCode02:两数相加
    LeetCode01:两数之和
    单链表类,链表逆置
  • 原文地址:https://www.cnblogs.com/huiji12321/p/11196837.html
Copyright © 2011-2022 走看看