第 14 章 结构和其他数据形式(names3)

 1 /*-----------------------------------
 2     names3.c -- 使用指针和 malloc()
 3 -----------------------------------*/
 4 
 5 #include <stdio.h>
 6 #include <string.h>        //提供 strcpy()、strlen() 原型
 7 #include <stdlib.h>        //提供 malloc()、free() 原型
 8 
 9 #define SLEN 81
10 
11 struct namect
12 {
13     char *fname;        //fname、lname 分别保存内存分配的地址
14     char *lname;
15     int letters;
16 };
17 
18 void getinfo(struct namect *);        //分配内存
19 void makeinfo(struct namect *);
20 void showinfo(const struct namect *);
21 void cleanup(struct namect *);
22 char* s_gets(char *st, int n);
23 
24 int main()
25 {
26     struct namect person;
27 
28     getinfo(&person);
29     makeinfo(&person);
30     showinfo(&person);
31     cleanup(&person);
32 
33     return 0;
34 }
35 
36 void getinfo(struct namect *pst)
37 {
38     char temp[SLEN];
39 
40     printf("Please enter your first name.\n");
41 
42     s_gets(temp, SLEN);
43     pst->fname = (char*)malloc((strlen(temp) + 1) * sizeof(char));
44     strcpy(pst->fname, temp);
45 
46     printf("Please enter your last name.\n");
47 
48     s_gets(temp, SLEN);
49     pst->lname = (char*)malloc((strlen(temp) + 1) * sizeof(char));
50     strcpy(pst->lname, temp);
51 }
52 
53 void makeinfo(struct namect *pst)
54 {
55     pst->letters = strlen(pst->fname) + strlen(pst->lname);
56 }
57 
58 void showinfo(const struct namect *pst)
59 {
60     printf("%s %s, your name contains %d letters.\n"
61         , pst->fname, pst->lname, pst->letters);
62 }
63 
64 void cleanup(struct namect *pst)
65 {
66     free(pst->fname);
67     free(pst->lname);
68 }
69 
70 char* s_gets(char *st, int n)
71 {
72     char *ret_val;
73     char *find;
74 
75     if (ret_val = fgets(st, n, stdin))
76     {
77         if (find = strchr(st, '\n'))
78             *find = '\0';
79         else
80             while (getchar() != '\n') continue;
81     }
82 
83     return ret_val;
84 }
names3.c

猜你喜欢

转载自www.cnblogs.com/web1013/p/9178481.html
今日推荐