结构体定义

有三种定义方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Student{
char *name;
int id;
int high;
}stu;//其中stu为结构体变量,Student为结构体名字,这个结构体名字可以省略,于是就有第二种定义法

struct {
char *name;
int id;
int high;
}stu;

//也可以不省去结构体名称,在接下来的步骤中去定义变量
struct Student{
char *name;
int id;
int high;
};
struct Student stu;

typedef

typedef可以重新定义结构体类型,简化定义变量时的步骤

1
2
3
4
5
6
typedef struct Student{
char *name;
int id;
int high;
}Student;//将struct Student类重新命名为Student
Student stu;//通过Student直接定义新的结构体变量

结构体嵌套

结构体是一种支持多层嵌套的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

typedef struct Birthday{
int year;
int month;
int day;
}Birthday;
typedef struct Student{
char *name;
int id;
int high;
Birthday birthday;//将结构体Birthday嵌套进Student中
}Student;
Student stu;
//访问
printf("student name:%s student birthday:%d-%d-%d",stu.name,stu.birthday.year,stu.birthday.month,stu.birthday.day);

结构体数组

结构体也是一种类型,所以可以使用数组来储存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>

typedef struct Student{
char *name;
int id;
int high;
}Student;
void printStudentinfo(Student *stu,int len)
{
for(int i=0;i<len;i++)
printf("name:%s\tid:%d\thigh:%d\n",(stu+i)->name,(stu+i)->id,(stu+i)->high);//若用指针访问元素则用->,若用数组访问可以用stu[i].name
}
int main()
{
Student stus[]={
{"zhangsan",01,190},
{"lisi",02,192}
};//定义结构体数组
printStudentinfo(stus,2);//利用函数打印结构体数组
return 0;
}

位域

通过位域可以指定使用空间储存的位数

1
2
3
4
5
6
7
8
9
10
struct {
int a:4;//规定a不能超过4位
unsighed b:1;//规定b不能超过1位
}bit,*pbit;

bit.a=8;//若bit.a大于8,则只会留下位域内的值,其余值将丢弃
bit.b=1;
pbit=&bit;
pbit->a=9;//此步超过了位域,则pbit->a变为0,因为9用二进制表示为10000

结构体题型后续更新……