//C primer plus
//结构中使用指针
//给结构中指针分配内存空间
//free释放掉之前分配的内存空间
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tsong.h"
struct namect{
char * fname;
char * lname;
int letters;
};
void getinfo(struct namect *); //输入姓名
void makeinfo(struct namect *); //计算长度
void showinfo(const struct namect *); //打印结构中的信息
void cleanup(struct namect *); //释放内存
int main(){
struct namect person;
getinfo(&person) ;
makeinfo(&person);
showinfo(&person);
cleanup(&person);
return 0;
}
void getinfo(struct namect *pst)
{
char temp[81];
puts("please enter your first name");
gets(temp);
pst->fname=(char *)malloc(strlen(temp)+1);
strcpy(pst->fname,temp);
puts("please enter your last name");
gets(temp);
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(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);
}
//结构中使用指针
//给结构中指针分配内存空间
//free释放掉之前分配的内存空间
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tsong.h"
struct namect{
char * fname;
char * lname;
int letters;
};
void getinfo(struct namect *); //输入姓名
void makeinfo(struct namect *); //计算长度
void showinfo(const struct namect *); //打印结构中的信息
void cleanup(struct namect *); //释放内存
int main(){
struct namect person;
getinfo(&person) ;
makeinfo(&person);
showinfo(&person);
cleanup(&person);
return 0;
}
void getinfo(struct namect *pst)
{
char temp[81];
puts("please enter your first name");
gets(temp);
pst->fname=(char *)malloc(strlen(temp)+1);
strcpy(pst->fname,temp);
puts("please enter your last name");
gets(temp);
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(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);
}