【1】结构体
struct 结构体类型名 {
数据类型 成员名1;
数据类型 成员名2;
...
数据类型 成员名n;
}s1;
struct stu s2;
【2】访问成员
变量名.成员名
【3】初始化
struct 结构体名 变量名={初始数据表};
struct 结构体名
{
成员列表;
}变量名 = {初始数据表};
【4】无名结构体
1--- 没有结构体类型名
2--- 不可以定义局部变量
【5】结构体嵌套
1--- 成员所属的数据结构类型是结构体类型
2--- 内部的结构体通常定义为无名结构体
【6】结构体数组
struct stu s[5];
本质是数组,元素是结构体类型
【7】 结构体指针
struct stu
{
int id;
}s1;
struct stu *p;
p = &s1;
【8】共用体
不同数据类型的数据可以使用共同的存储区域,这种数据构造类型成为共用体,简称共用,又称联合体。
union 共用体名
{
成员列表;
};
测试共用体的大小,以最大的成员所占的空间为准。
【9】typedef
用于给已存在的类型名,进行重命名。
源码及注释
1、1_struct.c
#include <stdio.h>
#include <string.h>
#define N 32
struct stu //struct:关键字
//stu:类型名
//id:成员名
//s1:变量名
{
int id;
float score;
char name[N];
}s1; //结构体是类型,s1是变量名字,s1全局
int main(int argc, const char *argv[])
{
struct stu s2; //s2局部变量,如果声明结构体的时候没有
//stu,则不能通过这种方式定义。
s1.id = 1;
s1.score = 972;
strcpy(s1.name,"saber"); //不能name[N] = "saber",只能出现在初始化
printf("id = %d\n",s1.id);
printf("sc = %.2f\n",s1.score);
printf("na = %s\n",s1.name);
s2.id = 8;
s2.score = 666;
strcpy(s2.name,"evil"); //不能name[N] = "saber",只能出现在初始化
printf("id = %d\n",s2.id);
printf("sc = %.2f\n",s2.score);
printf("na = %s\n",s2.name);
return 0;
}
2、2_struct_init.c
#include <stdio.h>
#include <string.h>
#define N 32