• C结构体struct用法小结


    结构体和int,float等类型一样是一种常用的类型,它是由各种基本数据类型构成,通常包含有struct关键字,结构体名,结构体成员,结构体变量。

    一.结构体定义


    通常有3种定义方式,以例子方式表示:

    1. 含有结构体名和结构体变量

    struct student{
        char name[20];
        int age;
        float height;
    }xiaoming;

    2.含有结构体名,无结构体变量

    struct student{
        char name[20];
        int age;
        float height;
    };

    之后便可以这个结构体去定义变量

     struct student xiaoming; 

    3.无结构体名,有结构体变量

    struct{
        char name[20];
        int age;
        float height;
    }xiaoming;

    二.结构体使用

    1.结构体成员表示

    表示为:
    结构变量.结构体成员
    例如:xiaoming.name

    2.结构体赋值
    例如:  xiaoming.age = 18; 
    也可以整体赋值:
     struct student xiaoming = {"xiaoming",18,175}; 

    三.结构体数组

    struct student{
        char name[20];
        int age;
        float height;
    }stu[50];

    这样就定义了一个结构体数组,相当于定义了一个数组,每个数组元素都是一个结构体

    例如 stu[0].name

    stu[0]是一个结构体,name是它的结构体成员

    四.结构体指针

    struct student{
        char name[20];
        int age;
        float height;
    }*stu;

    stu是一个结构体指针,通过形如stu->age的方式访问成员

    stu->age相当于(*stu).age
    值得一提的是,结构指针是指向结构的一个指针, 即结构中第一个成员的首地
    址, 因此在使用之前应该对结构指针初始化, 即分配整个结构长度的字节空间
    例如:
     student=(struct string*)malloc(size of (struct string)); 
    五.结构体嵌套
    即结构体中含有结构体

    struct family{
        char address[20];
        int people_num;
    }fy;
    struct student{
        char name[20];
        int age;
        float height;
        struct family fy;
    }xiaoming;

    可通过xiaoming.fy.people_num = 3;赋值

    参考资料:http://blog.csdn.net/tuoguang/article/details/46928481

  • 相关阅读:
    IDEA搭建普通java项目
    反射的学习
    解决Eclipse中文文档注释错位-处女座的悲哀!
    maven私服的搭建
    Springboot简介01
    git初识
    Servlet学习系列1
    搭建和启动javaWeb项目
    IDEA快捷键使用说明
    1.6 比较、掩码和布尔逻辑
  • 原文地址:https://www.cnblogs.com/jiduxia/p/7569561.html
Copyright © 2020-2023  润新知