zoukankan      html  css  js  c++  java
  • 结构体 + typedef

    简单结构体

    struct student{

      char name[20];   //可以用scanf或者直接赋值    

        *如果用char *name  在用scanf时没有内存接收

      long id;

      int age;

      float height;

    };

    结构体中只能声明变量不能赋初值。

    struck student zhangsan;

    struck student zhangsan = {"xiaowang",2000002,20,180.5};

    结构体的访问用".":xiaowang.name


    typedef

    typedef  struct student{

      char name[20];   //不能用char *name  在用scanf时没有内存接收

      long id;

      int age;

      float height;

    }Student;     // typedef给一个存在的类型取一个别名

    Student zhangsan;

    Student zhangsan = {"xiaowang",2000002,20,180.5};

    如果不加typedef:

    struct student{

      char name[20];   //不能用char *name  在用scanf时没有内存接收

      long id;

      int age;

      float height;

    }Student;//Student 是一个变量了


    结构体指针

    Student *s;

    如果*name是字符串      s->name = "xiaowang";

    如果name[]是数组接收  strcpy(s->name,"xiaowang");

    s->age = 23;

    Student *s[5]; //每一块都存着结构体的地址

    Student xw ={"xiaowang",2345,23,164.3};

    s[0] =&xw;  //结构体指针数组里面的每一个都存着地址,如果不给他内存地址,它的值就为空,不可直接赋值。

    s[0]->age = 20;


    结构体数组

    Student array[5] ={};

    strcpy(array[0].name,"xiaowang");

    array[0].age = 23;


    计算结构体内存空间

      如果结构体内部拥有多种数据类型,那么以占据内存字节数最高的类型对齐

    typedef struct{

        char *name;

        int age;

    }Person;//16

    char * 占据8个字节, int 占据4个字节

    所以age变量自动向name对齐。整个占据16个字节

     typedef struct{

        char name;

        int age;

    }Person;//8

     typedef struct{

        char name[2];

        int age;

    }Person;//8

     typedef struct{

        char name[6];

        int age;

    }Person;//12

  • 相关阅读:
    WPF 基于 Azure 的认知服务 情绪分析 语言检测 关键短语提取
    白板类应用的模式交互设计方案
    dotnet Multi-platform App UI 多平台应用 UI 框架简介
    Windows 窗口样式 什么是 WS_EX_NOREDIRECTIONBITMAP 样式
    Windows 对全屏应用的优化
    GitHub Action 新上线 WPF .NET Core 自动构建模板
    为何 WPF 对 vcruntime140 有引用
    用 C# 写脚本 如何输出文件夹内所有文件名
    排序、去重与离散化
    二分
  • 原文地址:https://www.cnblogs.com/huoran1120/p/5039231.html
Copyright © 2011-2022 走看看