结构体
一、为什么会出现结构体?
数据结构中的"个体"是用结构体来表示的,在 C++ 之中是用类表示的;
例如:对于存储表示一个 Student 的数据,需要:int id; char name[2000]; int age;即总共需要多个数据来"表示"一个学生,就像是 一个类,但是没有方法。
class Student
{
int id;
char name[2000];
int age;
void inputStudent()
{
}
void showStudent()
{
}
}
//这是一个"类", 用类把属性和操作(方法)组合在一起
struct Student
{
int id;
char name[2000];
int age;
}; //注意这里有一个分号!!!
这是结构体,面向过程语言中应用算法
二、什么叫结构体
结构体是用户根据实际需要自己定义的复合数据类型
#include <stdio.h>
#include <string.h>
//定义了数据类型,叫:"struct Student",而不是变量
struct Student
{
int id;//在C语言中,这个不叫属性,叫成员
char name[200];
int age;
} ; //分号不能省 !!
int main(void)
{
//@输出—1
struct Student st={1000,"zhangsan",20};
printf("%d % s %d\n", st.id, st.name, st.age);
//不能直接使用st,必须带点"."
//@输出—2
st.id= 99;
//st.name ="lisi"; //error
strcpy (st.name, "lisi");
st.age= 21;
printf ("%d %s % d\n", st.id, st.name, st.age);
return 0;
}
三、如何使用结构体
struct Student
{
int id;
char name[200];
int age;
} ;
int main(void)
{
struct Student st={1000,"zhangsan",20};
//st.id=99;//第一种方式
struct Student *pst;
pst =&st;
pst->id = 99;//第二种方式
//pst->id等价于(*pst).id 而 (*pst).id等价于 st.id,所以 pst->id等价于st.id
return 0;
}
总结:有两种方式可使用结构体 (见下)
struct Student st={1000,"zhangsan",20};
struct Student *pst=&st;
1\ st.id;
2\ pst->id;
pst 所指向的结构体变量中 id 这个成员
四、注意事项
1、结构体变量不能四则运算, 但可以相互赋值.
2、普通结构体变量和结构体指针变量作为函数传参问题