c语言结构类型

1.枚举

  常量符号化:const int yellow =1;

  枚举是一种用户定义的数据类型,声明语法如下:

    enum 枚举类型名字{名字0,名字1...};  //枚举类型名字可以省略

  我们使用的是名字0,1...,他们都是int 类型,值默认从0到n

  也可以指定值:

    enum color{red=1,yellow,blue=4};  //yellow=2,因为red=1

  声明枚举类型变量:

    enum color{red,yellow,blue};

    enum color c;

2.结构体

  struct 结构体名(可以省略,省略之后表示无名结构体,不能声明变量,只能在定义结构体的时候后面加变量){

    变量1,2,3...;

  }p1,p2(同时声明两个该种类型的结构体变量,可以省略);

  声明结构体变量:

    struct 结构体名 变量名;

  访问结构体成员变量

    结构体名.变量名

  结构体初始化:

    struct date{

      int month;

      int day;

      int year;

    };

    struct date d1={07,31,2014};

    struct date d2={.month=07,.year=2014};    //未给定的值默认是0,和数组初始化类似

  结构运算:  赋值、取地址、传递给函数作为参数

    赋值:

      struct point{

        int x;

        int y;      

      }p1,p2;

      p1=(struct point){5,10};  //强制类型转换,相当于p1.x=5,p1.y=10;

      p2=p1;         //相当于p1.x=5,p1.y=10;

  结构变量的名字并不表示结构变量的地址,取地址需要使用&符号。

    struct date *pDate=&today;

3.结构体作为函数参数

  结构体作为函数参数的时候是值传递

  结构体也可以作为返回类型

4.结构数组

  

struct date{
    
    int month;

    int day;

    int year;

};
struct date dates[100];    //ok
struct date dates[]={{4,5,2005},{2,4,2005}};    //ok

5.结构体中可以嵌套结构体

  r为结构体,r中有pt1另一个结构体,pt1中含有int类型的变量x,y

  rpt是指向r的指针,通过rpt访问pt1中的x: rpt->pt1.x

  不存在rpt->pt1->x

6.自定义数据类型 关键字typedef

  typedef可以用来声明一个已有变量类型的新名字

  如  typedef int Length;    //Length是int的一个别名

  typedef用于结构体(这样可以省略声明结构体变量前面的struct关键字)

  

typedef struct ADate{
    
    int month;

    int day;

    int year;

}Date;
Date d={1,20,2005};    

7.union

  union Name{

    int a;

    char[4] b;

  }

  a,b共享一块内存

  union最常见的用法就是上述这种,通常用于将数据对应的十六进制读入文件等

原文地址:https://www.cnblogs.com/foodie-nils/p/13557559.html