结构体(C++中用类也能实现)
为什么会出现结构体
为了表示一些复杂的数据,而普通的基本类型变量无法满足要求
什么叫结构体
结构体是用户根据实际需要自己定义的复合数据类型
如何使用结构体
两种方式:
struct Student st = {1000, "zhangsan", 20}
struct Student * pst = &st;
1. st.sid
2. pst->sid
pst所指向的结构体变量中的sid这个成员
注意事项:
结构体变量不能加减乘除,但可以相互赋值
普通结构体变量和结构体指针变量作为函数参数的传递
#include <stdio.h> #include <string.h> struct Student { int sid; char name[200]; int age; }; void assign (struct Student * pst); void print (struct Student *pst); void printVariable (struct Student pst); int main(void) { struct Student st; assign(&st); print(&st); printVariable(st); return 0; } void assign (struct Student * pst) { (*pst).sid = 100; strcpy(pst->name, "zhangsan"); pst->age = 10000; } void print (struct Student *pst) { printf("结构体的成员变量为: %d, %s, %d ", (*pst).sid, (*pst).name, (*pst).age); } /** 不建议, 耗内存, 耗时间*/ void printVariable (struct Student pst) { printf("结构体的成员变量为: %d, %s, %d ", pst.sid, pst.name, pst.age); }