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 跟这种方式相比到底效率相差多少。
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 跟这种方式相比到底效率相差多少。