C语言基础-结构体

结构体

定义:用户自定义的数据类型,在结构体中可以包含若干不同数据类型的成员变量(也可以相同),使这些数据项组合起来反映某一个信息。

格式:

struct 结构体名

{

   数据类型   成员变量1;

   数据类型   成员变量2;

   数据类型   成员变量3;

};

 结构体变量

概念:通过结构体类型定义的变量。

格式:struct  结构体名   变量名;

  • 先定义结构体,再定义结构体变量

struct 结构体名

{

      成员变量;

};

struct   结构体名   变量名;

  • 定义结构体的同时,定义结构体变量

struct  结构体名

{

      成员变量;

}变量名;

  • 缺省结构体名定义结构体变量

struct

{

      成员变量;

}变量名;

赋值

  • 定义变量时直接用大括号赋值

struct student

{

      int id;

      int age;

      float score;

      char name[32];

};

struct   student  stu={1,20,76,"zhangsan"};

  • 定义变量时未初始化,然后对变量单独赋值

struct student

{

      int id;

      int age;

      float score;

};

struct   student  stu;

stu.id=2;

stu.age=56;

stu.score=20;

  • 点等法赋值

struct student

{

      int id;

      int age;

      float score;

};

struct   student  stu={

               .id = 3,

               .age = 30,

               .score = 90

};

重定义typedef

  • 定义结构体的同时重定义

typedef struct student

{

      int id;

      int age;

      float score;

}STU;

struct student stu;//  == STU stu;

  • 先定义结构体,然后重定义

struct student

{

      int id;

      int age;

      float score;

};

typedef  struct student  STU;

STU stu;

结构体数组

概念:结构体类型相同的变量组成的数组。

定义格式:

  • 定义结构体同时定义结构体数组

struct student

{

      int id;

      int age;

      float score;

}stu[5];

  • 先定义结构体,然后定义结构体数组

struct student

{

      int id;

      int age;

      float score;

};

struct student stu[5];

初始化

  • 定义结构体同时赋值

struct student

{

      int id;

      int age;

      float score;

}stu[5]={

   {1,20,56},

   {2,21,57},

   {3,22,57},

   {4,29,57},

   {5,23,57}

};

  • 先定义结构体数组,再对数组的每一个元素分别赋值

struct student

{

      int id;

      int age;

      float score;

}stu[5];

stu[0].id=1;

stu[0].age=20;

stu[0].score=98.6

结构体数组输入输出(for循环)

struct student

{

      int id;

      int age;

      float score;

}stu[5];

int i;

for(i=0;i<5;i++)

scanf("%d %d %f",&stu[i].id,&stu[i].age,&stu[i].score);

结构体指针

概念:指向结构体变量的指针

定义格式:struct  结构体名  *结构体指针名;

赋值:指针变量名->成员变量名   例:p->id = 1;

大小:本质是指针,4字节

结构体大小

  • 字节对齐原则

用结构体里面最大的数据类型的大小和4进行比较,按照字节数小的为单位开辟空间,结构体的大小必须满足所有成员(不考虑数组和内套结构体)的整数倍.

  • 节省空间原则

减少空间浪费

struct std
{
    char ch;
    short a;
    double d;
    int b;   
}

//大小为16

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值