/*-----------------------------------
names3.c -- 使用指针和 malloc()
-----------------------------------*/ #include <stdio.h>
#include <string.h> //提供 strcpy()、strlen() 原型
#include <stdlib.h> //提供 malloc()、free() 原型 #define SLEN 81 struct namect
{
char *fname; //fname、lname 分别保存内存分配的地址
char *lname;
int letters;
}; void getinfo(struct namect *); //分配内存
void makeinfo(struct namect *);
void showinfo(const struct namect *);
void cleanup(struct namect *);
char* s_gets(char *st, int n); int main()
{
struct namect person; getinfo(&person);
makeinfo(&person);
showinfo(&person);
cleanup(&person); return ;
} void getinfo(struct namect *pst)
{
char temp[SLEN]; printf("Please enter your first name.\n"); s_gets(temp, SLEN);
pst->fname = (char*)malloc((strlen(temp) + ) * sizeof(char));
strcpy(pst->fname, temp); printf("Please enter your last name.\n"); s_gets(temp, SLEN);
pst->lname = (char*)malloc((strlen(temp) + ) * sizeof(char));
strcpy(pst->lname, temp);
} void makeinfo(struct namect *pst)
{
pst->letters = strlen(pst->fname) + strlen(pst->lname);
} void showinfo(const struct namect *pst)
{
printf("%s %s, your name contains %d letters.\n"
, pst->fname, pst->lname, pst->letters);
} void cleanup(struct namect *pst)
{
free(pst->fname);
free(pst->lname);
} char* s_gets(char *st, int n)
{
char *ret_val;
char *find; if (ret_val = fgets(st, n, stdin))
{
if (find = strchr(st, '\n'))
*find = '\0';
else
while (getchar() != '\n') continue;
} return ret_val;
}

names3.c

04-23 17:53