C语言结构体大全

一、结构体

1. 定义

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

2. 格式

struct 结构体名
{
    数据类型   成员变量1;
    数据类型   成员变量2;
    数据类型   成员变量3;
};

3、结构体变量

1.概念:通过结构体类型定义的变量;
2.格式:struct  结构体名   变量名;

1)先定义结构体,再定义结构体变量
    struct 结构体名
{
    成员变量;
};
struct   结构体名   变量名;

2)定义结构体的同时,定义结构体变量;
    struct 结构体名
{
    成员变量;
}变量名;

3) 缺省结构体名定义结构体变量
struct 
{
    成员变量;
}变量名;

4.赋值

1) 定义变量时直接用大括号赋值
struct student
{
    int id;
    int age;
    float score;
    char name[32];
};
struct   student  stu={1,20,76,"zhangsan"};

2)定义变量时未初始化,然后对变量单独赋值
struct student
{
    int id;
    int age;
    float score;
};
struct   student  stu;
stu.id=2;
stu.age=56;
stu.score=20;


3)点等法赋值
struct student
{
    int id;
    int age;
    float score;
};
struct   student  stu={
            .id = 3,
            .age = 30,
            .score = 90
};

5.访问

通过.访问:结构体变量名.成员变量名
printf("%d %d %lf\n",stu.id,stu.age,stu.score);
scanf("%d %d %lf %s",&stu.id,&stu.age,&stu.score,stu.name);

二、重定义typedef

1) 定义结构体的同时重定义

typedef struct student
{
    int id;
    int age;
    float score;
}STU;
struct student stu;//  === STU stu;

定义的同时重新定义赋值
STU stu={1,2,30};
STU* p = &stu;

2) 先定义结构体,然后重定义

typedef  struct student  STU;
STU stu;
意思是typedef加上头文件重新定义

三、结构体数组

1. 概念

结构体类型相同的变量组成的数组

2. 定义格式

1) 定义结构体同时定义结构体数组
struct student
{
    int id;
    int age;
    float score;
}stu[5];

2)先定义结构体,然后定义结构体数组
struct student stu[5];

3. 初始化

1) 定义结构体同时赋值
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}
};

2) 先定义结构体数组,再对数组的每一个元素分别赋值
struct student
{
    int id;
    int age;
    float score;
}stu[5];
stu[0].id=1;
stu[0].age=20;
stu[0].score=98.6;

4. 大小

结构体类型大小*元素个数
sizeof

5. 结构体数组输入输出(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);

四、结构体指针

1. 概念

指向结构体变量的指针

2. 定义格式

struct  结构体名  *结构体指针名;

struct student
{
    int id;
    int age;
    float score;
}stu1,stu2;
 struct work
{
    int id;
    int age;
    float score;
}w1,w2;
struct student *p = &stu1;
struct student *p1 = &w1;//错误,结构体类型不同

3. 赋值

格式:指针变量名->成员变量名
p->id = 1;
p->age = 23;
p->score = 98;
(*p).id = 2;

4. 大小

本质是指针,4字节

5、总结

1. 不能把结构体类型变量作为整体引用,只能对结构体类型变量中的各个成员变量分别引用
2. 如果成员变量本身属于另一种结构体类型,用若干个成员运算符一级级找到最低级的成员变量
3. 可以把成员变量当成普通变量运算
4. 再数组中,数组之间是不能彼此赋值的,结构体变量可以相互赋值

五、结构体大小

sizeof(struct 结构体名)


1) 字节对齐原则
用结构体里面最大的数据类型的大小和4进行比较
按照字节数小的为单位开辟空间
struct std
{
Char ch;
Short a;
Double d;
};    


2)节省空间原则
减少空间浪费

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值