自定类型有 数组、枚举、联合、结构体…
结构体,似乎,隐隐地带我向了更深一层
1. 结构体是什么
结构体:由一批数据组合而成的结构型数据,每个数据称为“结构性数据”的“成员”(就像一个组织,由许多成员组成)
- 结构体的每个成员可以是 标量、数组、指针、其他结构体
- 正因结构体成员多样的特点,它常用于描述复杂对象
- 结构体类型和结构体变量不同,实现过程是这样:
2.1 结构体的声明与定义
- 声明自己的结构体类型
- 用自己的结构体类型创建一个此类型的变量
补充:声明不占用空间;定义占用空间
声明与定义的基本框架:
struct为结构体关键字,tag为结构体的标志,member-list为结构体成员列表,其必须列出其所有成员;variable-list为此结构体声明的变量
//struct - c语言定义结构体的关键字
//tag - 结构体标签
struct tag //声明了 标签为 “tag” 的结构体类型 struct tag
{
...
member_list;//成员列表——这里可以给出此类型的成员
...
}; variable_list;//变量列表——这里可以创建此类型的结构体变量
- 既然已经声明了一种类型了,那这样自然可行:
struct tag s1;//定义了一个 struct tag 类型的变量 s1
- 而且有些部分是可以省略的:
- 省略 tag
struct {
int a;
char b;
double c;
} s1;
- 省略 variable-list
struct A{
int a;
char b;
double c;
} ;
2.2 对结构体变量的赋值
所谓初始化,就是定义的同时赋值;赋值又是对原有值的改变
- 定义时直接赋值(初始化)——可以用 { }
补充:这种花括号赋值,是初始化列表,只能用在初始化时
struct stu
{
char name[20];
int age;
char id[20];
};
int main()
{
struct stu stu1 = { "bacon" , 18 , "191404" };
return 0;
}
- 定义完再赋值
struct stu
{
char name[20];
int age;
char id[20];
};
int main()
{
struct stu stu1;
strcpy(stu1.name, "bacon");
//stu1.name = "bacon";//err
stu1.age = 18;
strcpy(stu1.id, "8848");
//stu1.id = "8848";//err
return 0;
}
2.3 访问结构体成员
- 结构体变量访问成员
结构体变量.成员
struct stu
{
char name[20];
int age;
char id[20];
};
int main()
{
struct stu stu1 = { "bacon", 18, "191404" };
printf("name:%snage:%dnid:%s ", stu1.name, stu1.age, stu1.id);
return 0;
}
结果:
name:bacon
age:18
id:191404
- 结构体指针访问成员
struct stu
{
char name[20];
int age;
char id[20];
};
int main()
{
struct stu stu1 = { "bacon", 18, "191404" };
struct stu* p = &stu1;
printf("name:%snage:%dnid:%s ", p->name, p->age, p->id);
return 0;
}
2.4 结构体传参
struct stu
{
char name[20];
int age;
char id[20];
};
void print1(struct stu s1)
{
printf("%sn%dn%sn", s1.name, s1.age, s1.id);
}
void print2(struct stu* ps1)
{
printf("%sn%dn%sn", ps1->name, ps1->age, ps1->id);;
}
int main()
{
struct stu stu1;
strcpy(stu1.name, "bacon");
stu1.age = 18;
strcpy(stu1.id, "8848");
print1(stu1);//实参是结构体
print2(&stu1);//实参是结构体指针
return 0;
}
可以看到,两个打印函数都能完成任务。但,传结构体过去,空间和时间上都造成浪费(结构体变量压栈耗费时间)
结构体传参时,要传结构体地址
培根的blog,与你一同进步!



