zoukankan      html  css  js  c++  java
  • C语言结构体篇 结构体

    在描述一个物体的属性的时候,单一的变量类型是无法完全描述完全的。所以有了灵活的结构体变量。 结构体变量从意义上来讲是不同数据类型的组合,从内存上来讲是在一个空间内进行不同的大小划分。

    1.1 结构体类型变量的定义

     struct 结构体名{
          结构体成员;
      };
      ​
      struct student{
          unsigned int id;
          char name[10];
          float score[5];
          //...
      };

     

    1.2 结构体变量的声明

    定义了结构体变量后,并没有在内存中开辟相应的空间,只有声明了变量之后,才是开辟了相应的结构体空间。

      struct student stu1;
      struct student stu2;

     

    1.3 结构体成员变量的使用

      stu1.id = 10000;
      stu1.name = "kmist"
      stu1.score[1] = 100;
      //...

     

    1.4 ‘.’ 和 ‘->’ 的区别 如果发生了地址跳转,就使用->

      //定义一个student结构体
      struct student{
          long id;
          char name[10];
          //...
      };
      ​
      //定义一个class结构体,其中声明了student的结构体.
      struct class{
          int room;
          struct student stu1;
          struct student stu2;
      };
      ​
      //声明class 结构体变量
      struct class class1;
      class1.room = 1;    //直接成员变量用 .
      class1->stu1.id = 1001; //访问其他空间地址用 -> ,包括数组等.
      class2->stu2.id = 1002;
      ​

     

    1.5 结构体动态空间的划分

    有的时候只是临时需要申请一个动态空间,用完以后就可以释放,这样能节省程序运行时的内存空间.

      #include <stdlib.h>
      struct student *stu = (struct student *)malloc(sizeof(struct student));
      stu->id = 1001; //通过地址访问,用->
      printf("%d
    ",stu->id);
      free(stu);

     

    1.6 结构体数组

    结构体数组本质上也是数组,是开辟两个连续相同结构的空间.

      struct student{
          int id;
          char name[10];
      };
      ​
      struct student stu[2]={1001,"kmist"};
      struct student *p = stu;    //p = stu[0]; (p+1) = stu[1]
      //将stu[0] 里的内容拷贝到 stu[1]中
      //stu[1]->id = stu[0]->id; xx 这是错误的写法,结构体等空间的拷贝要用拷贝函数
      memcpy((p+1),p,sizeof(struct student));
      ​
      //使用
      printf("%d
    ",(p+1)->id);

     

     

  • 相关阅读:
    WCF 路由功能
    ado.net2.0的SqlTransaction使用方法
    IIS7、IIS8添加net.tcp协议报错 "未将对象引用设置到对象的实例。"
    windows phone 7 调用 wcf
    kettle连接mssql(Driver class 'net.sourceforge.jtds.jdbc.Driver' could not be found, make sure the 'MS SQL Server' driver (jar file) is installed)
    hive源码编译
    传奇1.76版本私服物品过滤单(去除祖玛级别)
    中国电信摘机系统xml
    初中英语
    视频播放器
  • 原文地址:https://www.cnblogs.com/kmist/p/10116860.html
Copyright © 2011-2022 走看看