一、前言
在前面,我们已经学习了数组。数组可以存储相同类型的数据变量,但是,有时,一个数据可能包含不同的数据类型,针对这一问题,提出结构体。结构体可以存储相同的数据类型。
二、定义结构体
2.1 格式
struct tag {
member-list
member-list
member-list
...
} variable-list ;
2.2 声明方法
上述三个标签至少出现两个
struct
{
int a;
char b;
double c;
} s1;
struct SIMPLE
{
int a;
char b;
double c;
};
struct SIMPLE t1, t2[20], *t3;
typedef struct
{
int a;
char b;
double c;
} Simple2;
Simple2 u1, u2[20], *u3;
2.3 结构体的嵌套与包含
2.3.1 嵌套
struct COMPLEX
{
char string[100];
struct SIMPLE a;
};
struct NODE
{
char string[100];
struct NODE *next_node;
};
2.3.2 包含
当两个结构体相互包含时,则需要对一个结构体进行不完整声明,如下所示:
struct B;
struct A
{
struct B *partner;
};
struct B
{
struct A *partner;
};
2.3.3 结构成员的初始化
- 代码实现:
#include "stdio.h"
#include "string.h"
struct people
{
char name[20];
int age;
}student = {"xiaomage",23};
int main(){
printf("name:%s\nage:%d\n****更改后*****\n",student.name,student.age);
strcpy(student.name,"xiaoma");
student.age = 22;
printf("name:%s\nage:%d\n",student.name,student.age);
}
- 运行结果:
name:xiaomage
age:23
****更改后*****
name:xiaoma
age:22
三、结构体与指针
- 代码实现:
#include "stdio.h"
#include "string.h"
struct People
{
char name[20];
int age;
};
int main()
{
struct People people;
strcpy(people.name, "xiaomage");
people.age = 23;
struct People *p;
p = &people;
printf("name:%s\nage:%d\n", p->name, p->age);
return 0;
}
- 运行结果:
name:xiaomage
age:23
|