我:“师弟,怎么又开始发呆呢?”
师弟:“师兄,上次不是程夏出了一道题么?让我实现记录班上学生的成绩,并对学生成绩排序。我实现了,但是她说不对,排序后,需要带上学生的详细信息,比如学号、名字、性别、成绩等信息。我在想c语言中,有没有什么可以实现类似的变量?”
我:“结构体变量就可以。”
结构体
在C语言中,结构体(Structure)是一种自定义数据类型,它允许你将多个不同类型的变量组合成一个单一实体。这堆变量被称为结构体的成员(Members)。结构体能够很好的模拟现实世界对象的属性。
基本语法为:
struct tag {
type member1;
type member2;
...
};
● struct 关键字是定义结构体的必须前缀。
● tag 是结构体的标签名,可选的,可用于后续声明结构体变量。
● member1, member2, … 是结构体的成员,代表了不同数据类型的变量。
比如学生信息你可以定义如下:
struct student {
int id; //学号
char name[32]; //名字
char sex[16]; //性别
int score; //成绩
};
结构体成员的初始化方式有3种,如下:
// 方式一
struct student s = {1, "chengxia", "boy", 90};
// 方式二
struct student s1 = {
.id = 1,
.name = "chengxia",
.sex = "boy",
.score = 90
};
// 方式三
struct student s2;
s2.id = 1;
strcpy(s2.name, "chengxia");
strcpy(s2.sex, "boy");
s2.score = 100;
结构体的访问方式有2种,如下:
struct student s = {1, "chengxia", "boy", 90};
//方式一 .访问
printf("%d\n", s.id);
//方式二 指针访问->
struct student *ps = &s;
printf("%d\n", ps->id);
结构体作为函数参数
结构体也可以作为函数的参数传递,传递方式通常有两种:传值和传址(通过指针)。
● 传值:将结构体的副本传递给函数,函数中的修改不会影响原始结构体。
● 传址:将结构体的地址传递给函数,函数中的修改会直接影响原始结构体。
void change_id(struct student s) //传值
{
s.id = 2;
}
void change_id(struct student *s) //传址
{
s->id = 2;
}
结构体在网络通信中,应用比较多,典型的就是各个协议头的定义。如ip协议头。
struct iphdr
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
unsigned int ihl:4;
unsigned int version:4;
#elif __BYTE_ORDER == __BIG_ENDIAN
unsigned int version:4;
unsigned int ihl:4;
#else
# error "Please fix <bits/endian.h>"
#endif
u_int8_t tos;
u_int16_t tot_len;
u_int16_t id;
u_int16_t frag_off;
u_int8_t ttl;
u_int8_t protocol;
u_int16_t check;
u_int32_t saddr;
u_int32_t daddr;
/*The options start here. */
};
至于为什么会有这么复杂的定义,可以参考网络协议字节序/比特序的问题。