//使用指针和malloc()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 40
struct namect
{
char *fname;
char *lname;
int letters;
};
char *s_gets(char *st, int n);
void getinfo(struct namect *pst);
void makeinfo(struct namect *pst);
void showinfo(struct namect *pst);
void cleanup(struct namect *pst);
int main(void)
{
struct namect person;
getinfo(&person);
makeinfo(&person);
showinfo(&person);
cleanup(&person);
return 0;
}
void getinfo(struct namect *pst)
{
char temp[LEN];
printf("请输入fname: ");
s_gets(temp, LEN);
pst->fname = (char *)malloc(strlen(temp) + 1);
strcpy(pst->fname, temp);
printf("请输入lname: ");
s_gets(temp, LEN);
pst->lname = (char *)malloc(strlen(temp) + 1);
strcpy(pst->lname, temp);
}
void makeinfo(struct namect *pst)
{
pst->letters = strlen(pst->fname) + strlen(pst->lname);
}
void showinfo(struct namect *pst)
{
printf("%s %s, 你的名字包含%dletters.\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;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
运行案例: