<深入理解C指针>学习笔记和总结 第六章 指针和结构体

8 篇文章 0 订阅
7 篇文章 1 订阅
1 结构体的声明方式
typedef struct_name{
元素
}st_t;
以后再声明结构体变量 st_t 变量名;
2结构体中分配内存:
typedef struct_a
{
    char *fname;
    char *lname;
    char *title;
    short age;
}st_t;
void initializest_t(st_t *person,const char *fn,const char *ln,const char *title,short age)
{
    person->fname=(char *)malloc(strlen(fn)+1);
    strcpy(person->fname,fn);
    person->lname=(char *)malloc(strlen(ln)+1);
    strcpy(person->lname,ln);
    ...之后类似

使用:
st_t person;
initializeest_t(&person,"Peter","Underwood","Manager",36);


使用完了 记得free掉。 


3避免malloc/free开销中:
重复分配然后释放结构体会产生一些开销。可能导致巨大的性能瓶颈。解决这个问题的方法是为分配的结构体单独维护一个表,当用户不再需要某个结构体实例的时候,将其返回到结构体池中。
说明实例:
#define LIST_SIZE 10
st_t *list[LIST_SIZE];


void initializelist(void)
{
    int i;
    for(i=0;i<LIST_SIZE;i++)
list[i]=NULL;
}
st_t *getperson()
{
    int i;
    st_t *ptr;
    for (i=0;i<LIST_SIZE;i++)
    {
if(list[i]!=NULL)
{
   ptr=list[i];
   list[i]=NULL;
   return ptr;
}
    }
    st_t *person=(st_t *)malloc(sizeof(st_t));
    return person;
}
st_t *returnperson(st_t *person)
{
    int i;
    for(i=0;i<LIST_SIZE;i++)
    {
if(list[i]==NULL)
{
   list[i]=person;
   return person;
}
    }
    deallocateperson(person);//里面是free掉占用内存。
    free(person);
    return NULL;
}




应用:
initializelist();
st_t *ptrperson;
ptrperson=getperson();
initializeperson(ptrperson,"ralph","fitsgerald","mr",35);
displayperson(*ptrperson);
returnperson(ptrperson);
问题1:表的长度。
2 不知道free 与malloc  跟这种方式相比到底效率相差多少。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值