C语言结构体必知必会

结构体

结构体是一种特殊类型,可以打包其它类型为一种复合类型。在面向对象的概念中,就是一种特殊类。

使用结构体几种形式:

第一种

先定义结构体,然后定义结构体变量。

定义结构体:


struct point1{

    int x;

    int y;

};

定义结构体变量

struct point1 point;

第二种

定义匿名结构体,然后定义结构体变量


struct{

    int x;

    int y;

}point2;

第三种

定义结构体的同时定义结构体变量


struct point3{

    int x;

    int y;

}point;

第四种

用typedef定义结构体


typedef struct point4{

    int x;

    int y;

}t_point;

然后用t_point定义结构体变量

t_point point;

结构体数组


    struct student{

        int age;

        char *name;

    };

    struct student ss[10];

结构体指针


    struct student *pst;

    pst = &foo;

结构体初始化

有结构体定义


    struct student{

        int age;

        char *name;

    };

第一种


    struct student foo1 = {11, "xiaoming"};
    struct student foo2 = {11}

第二种


    struct student foo3 = {.age = 11};

第三种

    struct student foo4 = (struct student){11, "xiaoming"};

    struct student foo5 = (struct student){.age = 11};

结构体数组初始化


    struct student ss1[10] = {0};

    struct student ss2[10] = {{}, {}, {}};

    struct student ss3[10] = {[2] = {}, [3] = {}};

    struct student ss4[10] = {[2].age = 10, [3].name = "xiaoming"};

访问结构体成员

使用“.”返回结构体成员


    struct student foo = {11, "xiaoming"};

    int age = foo.age;

    char *name = foo.name;

    printf("age is %d, name is %s\n", age, name);



    foo.age = 20;

    foo.name = "liyong";



    printf("age is %d, name is %s\n", foo.age, foo.name);

当使用结构体指针的时候可以用箭头操作符”->”


    struct student *pst;

    pst = &foo;

    printf("pst age is: %d and name is %s\n", (*pst).age, (*pst).name);

    printf("pst age is: %d and name is %s\n", pst->age, pst->name);
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值