struct为结构体关键字,tag为结构体的标志,member-list为结构体成员列表,其必须列出其所有成员;variable-list为此结构体声明的变量。
struct tag
{
member-list;
} variable-list ;
示例代码:
struct Student
{
char name[10];
int age;
int score[5];
}stu1;
结构体的2种定义方式:
1. 常规定义:
struct Student
{
char name[20];
int age;
int score[5];
};
struct Student s1 = {"zhangsan",22,{1,2,3,4,10}};
2.尾部定义
struct
{
char name[10];
int age;
int score[5];
}stu1 = {"张三",20,{150,110,20,34,114}},stu2;
结构体之间可以相互赋值
stu1 = stu2;此时stu2 ={"张三",20,{150,110,20,34,114}};
无名结构体,只能通过尾部定义创建对象
struct
{
char name[20];
int age;
int score[5];
}s1,s2,s3;
通过结构体指针动态创建对象
struct Student
{
char name[20];
int age;
int score[5];
}*s;
s = (struct Student*)malloc(sizeof(struct Student));
结构体的成员可以包含其他结构体(结构体的嵌套),也可以包含指向自己结构体类型的指针,而通常这种指针的应用是为了实现一些更高级的数据结构如链表和树等。
结构体的嵌套:
struct SIMPLE
{
char name[10];
}
struct COMPLEX{
char name[100];
struct SIMPLE i;
};
包含指针的结构体:
struct NODE{
char name[10];
struct NODE *next_node;
};
结构体对象如何访问内部元素;
静态对象:通过点运算符"."
struct
{
char name[20];
int age;
int score[5];
}s1 = {"张三,20,{150,110,20,34,114}"},*p;
void main()
{
p = &stu;
printf("%s",stu.name);
printf("%s",p->name);
}可以看到两个输出结果都是一样的;
动态对象:通过指向符"->"如果对象内部存在指针元素,那么在使用以前要分配内存空间;