数据结构学习(结构体复习)

来源:互联网 发布:linux查看系统进程命令 编辑:程序博客网 时间:2024/05/17 02:08

结构体

为什么会出现结构体

为了表示一些复杂的数据,而普通的基本类型变量无法满足要求

什么叫做结构体

结构体是用户根据实际需要自己定义的复合数据类型

如何使用结构体

两种方式:

struct Student st = {1000,"zhangxu",20};

struct Student *pst = &st;

1.

St.sid

2.

Pst->sid

Pst所指向的结构体变量中的sid这个成员

注意事项

1.结构体变量不能加减乘除,但可以相互赋值

2.普通结构体变量和结构体指针变量作为函数传参的问题

#include<stdio.h>
#include<string.h>
struct Student
{
 int sid;
 char name[200];
 int age;
};//分号不能省
int main(void)
{
 struct Student st = {1000,"zhangxu",20};
 printf("%d   %s   %d\n",st.sid,st.name,st.age);
 st.sid = 99;
 //st.name = "lisi";//error
 strcpy(st.name,"lisi");
 st.age = 22;
 printf("%d   %s   %d\n",st.sid,st.name,st.age);
 return 0;
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#include<stdio.h>
struct Student
{
 int sid;
 char name[200];
 int age;
};
int main(void)
{
 struct Student st = {1000,"zhangxu",20};
 //st.sid = 99;//第一种方式
 struct Student *pst;
 pst = &st;
 pst->sid = 99;//第二种方式 pst->sid等价于(*pst).sid,而(*pst).sid等价于 st.sid,所以 pst->sid等价于st.sid
 return 0;
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#include<stdio.h>
struct Student
{
 int sid;
 char name[200];
 int age;
};
int f(struct Student * pst);
int g(struct Student * st);
int main(void)
{
 struct Student st;//和 int i一样
 int i;//内存给分配空间了
 f(&st);
 g(&st);

 return 0;
}
int f(struct Student * pst)
{
 (*pst).sid = 99;
 strcpy(pst->name,"lisi");
 pst->age = 22;
}
int g(struct Student *st)
{
 printf("%d   %s   %d\n",st->sid,st->name,st->age);
}

 

原创粉丝点击