码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-10-30 20:12:00      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:image   png   microsoft   amp   get   soft   输入   代码   nbsp   

结构体的传值方法一共有三种形式,通过传递结构体传递指针传递结构体自身参数。传递指针的方式与另外两种方法最大的不同就是传递的实际上是结构体的地址,在传值的过程中,指针需要进过初始化分配内存(也就是使用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("请输入书名:\t");
41     gets(lib->title);
42     printf("请输入作者名:\t");
43     gets(lib->author);
44     printf("请输入书的价格:\t");
45     scanf("%f",&(lib->price));
46     return lib;
47 }
48 struct Book * showinfo(struct Book *lib)
49 {
50     printf("the title is %s \t and the author is %s \t and the price is %f ",
51                             lib->title,lib->author,lib->price);
52 }

运行结果为:

技术分享

 

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

标签:image   png   microsoft   amp   get   soft   输入   代码   nbsp   

原文地址:http://www.cnblogs.com/zhengzuozhanglina/p/6013596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!