结构体

结构体和类的区别:

  类里可以定义方法和属性,而结构体里只能有各种成员。

为什么有结构体:

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

什么是结构体:

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

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 struct Student
 4 {
 5     int sid;
 6     char name[200];
 7     int age;
 8 };  //分号不能省
 9 int main(){
10     struct Student st = {1000,"sun",20};
11     printf("%d %s %d",st.sid,st.name,st.age);
12     
13     st.sid=99;
14     //st.name="tom"; //在c语言里会报错
15     strcpy(st.name,"tom");//使用这个函数,将后者字符串复制给前者,此函数包含在string.h头文件中
16     st.age = 22;
17     
18     return 0;
19 }

 

为了不占用更多内存,使用结构体指针访问成员变量

 1 #include<stdio.h>
 2 struct Student
 3 {
 4     int sid;//占四个字节
 5     char name[200];//200个字节
 6     int age;//四个字节 
 7 };  //分号不能省
 8 int main(){
 9     struct Student st;
10     struct Student *pst;
11     pst = &st;
12     pst->sid=99;  //等价于(*pst).sid<<=>>st.sid
13     
14     return 0;
15 }

 

使用结构体的两种方式:

1 struct Student st;
2 
3 struct Student *pst = &st;
4 
5 1.st.sid;
6 
7 2.pst->sid; //pst所指向的结构体变量这的sid成员

 

注意事项:

  结构体变量之间只能相互赋值(可以在函数传实参的时候传递结构体变量名),不能加减乘除。 普通结构体变量和结构体指针变量作为函数传参的问题

posted @ 2019-07-27 17:58  孙晨c  阅读(267)  评论(0编辑  收藏  举报