• C语言结构体传值-->通过指针进行传值


    结构体的传值方法一共有三种形式,通过传递结构体传递指针传递结构体自身参数。传递指针的方式与另外两种方法最大的不同就是传递的实际上是结构体的地址,在传值的过程中,指针需要进过初始化分配内存(也就是使用malloc()函数分配空间给指针)

    来看看以下代码:

    有两个点需要注意:

            (1)在方法设置类型的时候 是一个struct Book 类型,同时还是一个指针的类型,可以说(struct Book && pointer类型)

            (2)在代码的32,33行处,声明了一个struct Book &&pointer类型的时候,一定要对指针类型做一次内存分配

     1 /*
     2 *该实例程序用来显示如何在方法体中传递结构体参数
     3  该传递参数的方法是通过指针的形式对参数进行传递
     4  getinfo()方法用于对结构体指针进行赋值操作
     5  showinfo()方法用于对结构体进行输出 
     6 */ 
     7 #include <stdio.h>
     8 #include <stdlib.h>
     9 #define MAX_SIZE 2
    10 #define MAX_TITLE_SIZE 30
    11 #define MAX_AUTHOR_SIZE 30
    12 //构造一个Book 类型的结构体
    13  /*
    14   *title 为char类型
    15    author char 类型
    16    price float 类型 
    17  */ 
    18 struct Book 
    19 {
    20     char title[MAX_TITLE_SIZE];
    21     char author[MAX_AUTHOR_SIZE];
    22     float price;
    23     
    24 }; 
    25 /*
    26   声明getinfo() showinfo()方法 
    27 */
    28 struct Book  * getinfo(struct Book *lib);
    29 struct Book * showinfo(struct Book  *lib);
    30 int main()
    31 {
    32     struct Book *lib;
    33     lib=(struct Book *)malloc(sizeof(struct Book));
    34     lib=getinfo(lib);
    35     showinfo(lib);
    36     return 0;    
    37 }
    38 struct Book * getinfo(struct Book *lib)
    39 {
    40     printf("请输入书名:	");
    41     gets(lib->title);
    42     printf("请输入作者名:	");
    43     gets(lib->author);
    44     printf("请输入书的价格:	");
    45     scanf("%f",&(lib->price));
    46     return lib;
    47 }
    48 struct Book * showinfo(struct Book *lib)
    49 {
    50     printf("the title is %s 	 and the author is %s 	 and the price is %f ",
    51                             lib->title,lib->author,lib->price);
    52 }

    运行结果为:

  • 相关阅读:
    makefile 中 $@ $^ %< 使用
    makefile中的自动化变量$@,$%,$
    linux grep命令
    wc命令
    linux下echo命令
    winscp和putty提取固件教程
    WinSCP和PuTTY在刷openwrt固件的使用教程
    OPENWRT学习笔记入门篇
    第五章 并发性:互斥和同步
    getCurrentSession()和getOpenSession()的区别
  • 原文地址:https://www.cnblogs.com/zhengzuozhanglina/p/6013596.html
Copyright © 2020-2023  润新知