zoukankan      html  css  js  c++  java
  • 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 }

    运行结果为:

  • 相关阅读:
    【解题报告】 洛谷P1663 山
    【解题报告】 洛谷P6733 间歇泉
    【解题报告】 洛谷P1542 包裹快递
    二分总结
    SmartSchool CC校友录V8(毕业入世版)
    Hide/Show running Console
    Calculate drive total/free/available space
    C# list installed softwares
    How to: Modify a Project System So That Projects Load in Multiple Versions of Visual Studio
    PS:WINRAR制作32位安装程序和64位安装程序选项
  • 原文地址:https://www.cnblogs.com/zhengzuozhanglina/p/6013596.html
Copyright © 2011-2022 走看看