C语言11 结构体

admin 2018年5月13日02:28:33评论507 views字数 1007阅读3分21秒阅读模式
摘要

思考:当需要一个容器能够存储1个字节,你会怎么做? //char
当需要一个容器能够存储4个字节,你会怎么做? //int
当需要一个容器能够存储100个2个字节的数据,你会怎么做? //short arr[100]

思考:

当需要一个容器能够存储1个字节,你会怎么做? //char
当需要一个容器能够存储4个字节,你会怎么做? //int
当需要一个容器能够存储100个2个字节的数据,你会怎么做? //short arr[100]

当需要一个容器能够存储5个数据,这5个数据中有1字节的,2字节的有10字节的。。。你会怎么做??

=====

结构体

我需要这样的一个容器:

生命  int 魔法  int 技能  int 经验  int 血值  int 等级  int 移动速度    float 名称  char[0x20]   char    =   容器 int    =   容器 数组    =   容器 结构体    =   容器

结构体的定义:

struct 类型名{     //可以定义多种类型     int a;     char b;     short c; };
  1. char/int/数组 等是编译器已经认识的类型:内置类型
  2. 结构体是编译器不认识的,用的时候需要告诉编译器一声:自定义类型
  3. 上面的代码仅仅是告诉编译器 我们自己定义的类型是什么样的,本身并不占用内存
  • 接口体声明位置拥有如同声明变量一样的属性 局部和全局
  • 结构体在定义的时候 除了自身以外,可以使用任何类型

结构体类型变量的定义:

struct stPoint {     int x;     int y; } //结构体类型 变量名;  struct stPoint stPoint; struct stPoint point = {10,20};   struct stStudent {     int stucode;     char stuName[20];     int stuAge;     char stuSex; }  struct stStudent student = {101,"张三",18,'M'};

结构体变量的读写:

struct stPoint {     int x;     int y; }  stPoint point = {10,20}; int x; int y;  //读 x =point.x; y = point.y;  //写 point.x = 100; point.y = 200; 

动手思考

struct stPoint {     int x;     int y; }      stPoint point = {10,20};     stPoint point2 = {11,20};     point = point2;          //可以吗? 

定义结构体类型的时候,直接定义变量

struct stPoint {     int x;     int y; }point1,point2,point3;  //这种方式是分配内存的,因为不仅仅是定义新的类型。还定义了三个全局变量  point1.x = 1; point1.y = 2;  point2.x = 3; point2.y = 4;  point3.x = 5; point3.y = 6;

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2018年5月13日02:28:33
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   C语言11 结构体http://cn-sec.com/archives/51484.html

发表评论

匿名网友 填写信息