9.3结构体

来源:互联网 发布:python代码运行 编辑:程序博客网 时间:2024/06/04 21:16

    9.3结构体

 》结构体,是一种构造数据类型


一、定义结构体

//1、定义一个学生类型的结构体 typedef struct{    int num;    char name[20];    char sex;    float score; }Student;     //结构体类型名Student

>>结构体定义不预留内存,仅描述了一个结构体的形式。要使用,需声明!

二、声明结构体 (三种方法)
     1、先定义结构体,再声明结构体变量。

struct Student{    int num;    char name[20];    char sex;    float score;};    Student stu1,stu2;

     Student stu1,stu2;     >声明的变量stu1,stu2为struct Student  类型

        或者:用typedef

typedef struct{    int num;    char name[20];    char sex;    float score;}Student;   Student stu1,stu2;

  Student stu1,stu2;   >声明的变量stu为Student 类型



     2、定义结构体同时说明结构体变量。    

struct Student{    int num;    char name[20];    char sex;    float score;}stu1,stu2; 


     3、直接声明结构体变量。    

struct {        int num;        char name[20];    char sex;        float score;}stu1,stu2; 
       >这种类型结构体只能使用一次,以后无法再定义该结构体变量。

- - - - --- - - - - -- - - - - - -- - - --  -- - --  --  -- --- - -- - -- - -- - - - -- - - - - - - -- - 
     另:嵌套的结构体

//包括年、月、日 结构体 typedef struct {    int year;    int month;    int day; }Date;
//一个学生类型的结构体 typedef struct{    int num;     char name[20];    char sex;    float score;    Date birthday;}Student; 


三、结构体变量的使用    

结构体变量名.成员名     

Student stu;

        stu.num       //stu的学号

        stu.birthday.month  //stu的月份      

四、结构体变量的初始化Student s1={1,”gq",'M',98,{1991,12,17}};

五、结构体变量赋值

    Student s2;

    s2.num=2;

    strcpy(s2.name,"Gavin");

   //为数组赋值

    s2.sex='F'

    s2.score=95;

    s2.birthday.year=1992;

    s2.birthday.month=1;

    s2.birthday.day=21;


六、结构体数组
/* ->>>>>>>>>>>>>> * 动态的为结构体数组赋值 */void dynamicStructValuation(){    Student arr[3];    //结构体数组    for (int i=0; i<3; i++) {        printf("请输入第%d个学生的学号,姓名,性别,成绩,出生日期:\n",i+1);         scanf("%d%s%c%c%lf%d%d%d",&arr[i].num,arr[i].name,&arr[i].sex,&arr[i].sex,&arr[i].score,&arr[i].birthday.year,&arr[i].birthday.month,&arr[i].birthday.day);    }    for (int i=0; i<3; i++) {            printf("学号:%d\t姓名:%s\t性别:%c\t成绩:%.2f\t出生:%d-%d-%d\n",arr[i].num,arr[i].name,arr[i].sex,arr[i].score,arr[i].birthday.year,arr[i].birthday.month,arr[i].birthday.day);    }       //计数总成绩    int sum=0;    for (int i=0; i<3; i++) {        sum+=arr[i].score;    }    printf("\n总成绩:%d\t平均分:%.2f\n",sum,sum/3.0);    }

      >定义结构体数组时,元素个数可以不指定:Student stu[]={{…},{…},{…},…}

七、结构体指针变量
      Student stu;     //结构体变量
      Student *pstu;   //结构体指针变量

   访问结构体变量成员:
     1)(*结构体指针变量). 成员名
     2)   结构体指针变量 -> 成员名
     (*pstu).num 
     pstu->num

     >把一个完整的结构体变量作为参数传递,费时间又费空间,开销大;
          >用结构体指针做函数参数,能提高程序的运行效率


另外:
#include <stdio.h>/* 1、枚举    enum sex{        male,        female    };*/typedef enum{    male,    female} sex;int main(int argc, const char * argv[]){    /*1、枚举实现  它的数据类型是enum sex        enum sex zs=male;    */        sex zs=male;        return 0;}


0 0
原创粉丝点击