菜鸟学习历程【9】结构体

来源:互联网 发布:网上域名注册管理系统 编辑:程序博客网 时间:2024/06/06 00:50
结构体

       结构体将一些相关联的数据打包成一个整体方便实用,例如我们教务系统中,涉及到学生的姓名、学号、成绩等。我们可以将这些信息打包成一个是整体,这个整体就被称为结构体。

一、声明格式
    struct   结构体名
    {
         成员列表;
    };
    需要注意的是,结构体的末尾有一个分号(;),这个分号必不可少。结构体也是一种数据类型,允许嵌套。
    例如:
struct  student{    int num;    char name[10];    char sex;    int age;    float score;};
二、定义变量

1.在main函数内定义:
   struct student  stu1,  stu2 ;
   struct student 必须连在一起,不可以分开
   因此,我们可以使用" typedef struct student STU; "这条语句,用STU代替typedef  struct student,在实际编程过程中,会节约很多时间。

2.写结构体时,直接定义:
   例如:
   struct  student
   {
        int id;
        char name[10];
        char sex;
   }stu1;
   我们在结构体最后的(;)前面可以直接定义变量。

三、结构体的使用
   
    例如定义一个stu1:

    scanf("%s%d   %c",stu1.name, &stu1.id, &stu1.sex );
    printf("%s%d    %c\n", stu1.name , stu1.id, stu1.sex );
   
    注意:不能将一个结构体变量作为一个整体进行输入输出,下面这样写是错误的:
    scanf("%s%d  %c", stu1);

    对于结构体指针,如:STU *stu1, *stu2,访问成员时,要用"->"
    scanf("%s%d   %c",stu1->name, &stu1->id, &stu1->sex );
    printf("%s%d    %c\n", stu1->name , stu1->id, stu1->sex );

四、使用malloc为结构体分配内存
   
#include <stdio.h>#include <stdlib.h>struct  student {        int id;        char *name;        char sex; };typedef struct student STU;int main(){    STU *stu1,  *stu2;    stu1 = (STU *)malloc(sizeof(STU));    stu1.name = (char *)malloc(sizeof(char));}
说明:使用malloc后,要用free释放内存,以免造成内存泄露。

五、struct结构体占字节数

struct  student
   {
        char name;
        int id;
        char sex;
   };
typedef  struct  student  STU;

 对于上面这个struct,sizeof(STU),结果是1+4+1=6???
 正确答案是:1+3+4+1+3=9-->12
 为什么呢?
 原因:结构体的总字节数应当是最长成员类型长度的倍数(double类型按照int类型结算),对于上面这个例题,首先定义一个char类型,占一个字节,但int类型前必须是4的倍数,即原本 一个char占一个字节,要补全4个字节后,再存放int,所以有了(+3),但int之后的就可以直接存放char。

struct  student
   {
        int id;
        char name;
        char sex;
   };
typedef  struct  student  STU;

对于上面这个struct,sizeof(STU),结果是4+1+1=6->8,所以最终结果是8;
 
struct  student
   {       
        char name[10];
        double  id;
   };

对于上面这个struct,sizeof(STU),结果是10+ 2 + 8 = 20

  struct  student
   {       
        char name[10];
        int id;
        char sex;
   };

 
typedef  struct  student  STU;

对于上面这个struct,sizeof(STU),结果是10 + 2 + 4 +1 +3  = 20;这里的+2,是为了int前满足字节数为4的倍数的要求,最后的+3也是为了满足这个要求。
  
结构体数组:和定义结构体一样,
struct student
{
    int num;
    char name[20];
    char sex;
    int age;
    float score;
    char addr[30];
 } stu[3];
定义了一个数组stu,数组有3个元素,均为struct student类型数据。



原创粉丝点击