8_结构体的使用概述
结构体
为什么会出现结构体:
为了表示一些复杂的数据,而普通的基本类型变量无法满足要求
什么叫做结构体:
结构体是用户根据实际需要自己定义的复合数据类型
如何使用结构体:
两种方式——
struct Student st={1000,”zhagnsan”,20};
struct Student*pst=&st;
1)
st.sid
2)
pst->sid
pst所指向的结构体变量中的sid这个成员
CASE 1
#include<stdio.h>
#include <string.h>
struct Student
{
intsid;
charname[200];
intage;
}; //分号不能省
Int main(void)
{
structStudent st={1000,”zhagnsan”,20};
printf(“%d,%s%d\n,”,st.sid,st.name,st.age);
printf(“%d,%s%d\n,”,st); //error
st.sid=99; //第一种
//st.name=”lisi”; //error
strcpy(st.name,”lisi”);
st.age=22;
structStudent*pst;
pst=&st; //第二种
pst->sid=99; //pst->等价于(*pst).sid,而(*pst).sid等价于st.sid,所以pst->sid等价于st.sid
Return0;
}
注意事项:
结构体变量不能加减乘除,但可以相互赋值
普通结构体变量和结构体指针变量作为函数传参的问题
CASE 2
void f(struct Student *pst);
void g(struct Student st);
void g2(struct Student *pst);
int main (void)
{
struct Student st; //已经为st分配好了内存
f(&st);
//g(st);
g2(&st);
// printf(“%d %s %d\n”,st.sid,st.name,st.age); //输出方法一
return 0;
}
void g(struct Student st) //整体变量赋值//输出方法二,速度慢,耗空间,耗内存,不推荐
{
printf(“%d%s %d\n”,st.sid,st.name,st.age);
}
void g2(struct Student *pst)
{
printf(“%d %s%d\n”,pst->sid,pst->name,pst->age);
}
void f(struct Student *pst)
{
(*pst).sid=99;
strcpy(pst->name,”zhagnsan”);
pst->age=22;
}