结构体struct

在网络协议、通信控制、嵌入式系统等我们需要传送的不是简单的字节流,而是包含了很多数据类型的一个整体。这时候,我们可以通过结构体来进行解决。

在结构体中,数据默认是共有的,可以进行直接的访问,而在类中,数据默认的是私有的。

结构体的定义如下:

[cpp]  view plain copy
  1. struct date  
  2. {  
  3.   
  4.     int year;  
  5.     int month;  
  6.     int day;  
  7. };  

也可以这样进行定义:

[cpp]  view plain copy
  1. struct date  
  2. {  
  3.   
  4.     int year;  
  5.     int month;  
  6.     int day;  
  7. }Date;  

当然也可以使用typedef进行定义


[cpp]  view plain copy
  1. typedef struct date  
  2. {  
  3.   
  4.     int year;  
  5.     int month;  
  6.     int day;  
  7. }Date,*pDate;  


而pDate = &Date;


结构体的定义本身是一条语句,所以要 以分号终止。

下面通过一个输出学生信息的程序来进行说明。


[cpp]  view plain copy
  1. #include<stdio.h>  
  2. #include<string.h>  
  3. void Print(struct Student*,int);  
  4.   
  5. struct Student  
  6. {  
  7.     char name[20];  
  8.     char sex;  
  9.     char num[15];  
  10.     char Tel[12];  
  11.   
  12.   
  13.   
  14. };  
  15.   
  16.   
  17. int main()  
  18. {  
  19.     const int Size = 3;  
  20.   
  21.     struct Student st[Size];  
  22.     Print(st,Size);  
  23.       
  24.     return 0;  
  25. }  
  26.   
  27. void Print(struct Student *pst,int size)  
  28. {  
  29.     int i = 0;  
  30.   
  31.   
  32. for(i =0;i< size; i++)  
  33.     {  
  34.         printf("请输入学生的姓名\n");  
  35.         scanf("%s",pst[i].name);  
  36.   
  37.         printf("请输入学生性别M(男)F(女)\n");  
  38.         scanf("%s",&pst[i].sex);  
  39.   
  40.         printf("请输入学生的学号\n");  
  41.         scanf("%s",&pst[i].num);  
  42.   
  43.         printf("请输入学生的电话号码\n");  
  44.         scanf("%s",pst[i].Tel);  
  45.       
  46.   
  47.   
  48.       
  49.   
  50.     }  
  51.   
  52.  for(i = 0;i<size; i++)  
  53.     {  
  54.         printf("学生的姓名:%s\n",pst[i].name);  
  55.           
  56.         printf("性别: %c\n",pst[i].sex);  
  57.   
  58.         printf("学号: %s\n",pst[i].num);  
  59.   
  60.         printf("电话: %s\n",pst[i].Tel);  
  61.       
  62.       
  63.   
  64.       
  65.     }  
  66.   
  67.   
  68.   
  69. }  

程序的输出结果是



需要注意的是:

scanf("%s",pst[i].name);输入时不用取地址符,因为name本身就是一个地址。

再者,在程序传递参数使注意。void Print(struct Student*,int);注意两个参数的类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值