• 技术文章 >C语言 >C语言教程

    c语言中使用指向结构指针的原因

    小妮浅浅小妮浅浅2021-10-26 15:48:19原创9621

    1、指向结构的指针通常比结构本身更容易控制。

    2、早期结构不能作为参数传递给函数,但可以传递指向结构的指针。

    3、即使可以传递结构,传递指针通常也更有效率。

    4、一些用于表示数据的结构包含指向其他结构的指针。

    实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    #include <stdio.h>

    #define LEN 20

      

    struct names                    //定义结构体names

    {

        char first[LEN];

        char last[LEN];

    };

      

    struct guy                      //定义结构体guy

    {

        struct names handle;

        char favfood[LEN];

        char job[LEN];

        float income;

    };

      

    int main(void)

    {

        struct guy fellow[2] = {   

            //这是一个结构嵌套,guy结构里嵌套了names结构

            //初始化结构数组fellow,每个元素都是一个结构变量

            {{"Ewen","Villard"},

            "girlled salmon",

            "personality coach",

            68112.00

            },

            {{"Rodney","Swillbelly"},

            "tripe",

            "tabloid editor",

            432400.00

            }

        };

      

      

        struct guy * him;       //这是一个指向结构的指针

        printf("address #1:%p #2:%p\n",&fellow[0],&fellow[1]);

        him = &fellow[0];       //告诉编译器该指针指向何处

        printf("pointer #1:%p #2:%p\n",him,him+1);//两个地址

        printf("him->income is $%.2f:(*him).income is $%.2f\n",him->income,(*him).income);//68112.00

        //指向下一个结构,him加1相当于him指向的地址加84。names结构占40个字节,favfood占20字节,handle占20字节,float占4个字节,所以地址会加84

        him++;    

        printf("him->favfood is %s: him->handle.last is %s\n",him->favfood,him->handle.last);

        //因为有了上面的him++,所以指向的是favfood1[1],

        return 0;

    }

      

      

      

      

    输出结果为

    PS D:\Code\C\结构> cd "d:\Code\C\结构\" ; if ($?) { gcc structDemo02.c -o structDemo02 } ; if ($?) { .\structDemo02 }

    address #1:000000000061FD70 #2:000000000061FDC4

    pointer #1:000000000061FD70 #2:000000000061FDC4

    him->income is $68112.00:(*him).income is $68112.00

    him->favfood is tripe: him->handle.last is Swillbelly

    以上就是c语言中使用指向结构指针的原因,希望对大家有所帮助。更多C语言学习指路:C语言教程

    专题推荐:c语言 指针
    上一篇:c语言中fwirte函数的使用 下一篇:c语言中预处理器是什么

    相关文章推荐

    • c语言中static修饰局部静态变量• c语言中static如何修饰函数• c语言中fopen函数的使用• c语言中abort函数的使用• c语言中全局变量的使用• c语言中局部变量是什么• c语言中assert函数是什么• c语言中assert函数的使用注意• c语言中exit函数是什么• c语言中exit和return的区别• c语言中main函数是什么• c语言中__cplusplus是什么• c语言中fwirte函数的使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网