发布时间: 2012-06-20 20:37:21 作者: rapoo
在C语言中大概实现VC++中的LISTARRAY功能方法(一)#ifndef __LISTARRAY_H__#define __LISTARRAY_H__#include "rtthread.h"#include "finsh.h"//LIST数组typedef struct _ListArray ListArray;struct _ListArray{ void **pListPointArray; //LIST数组指针 int Total; //元素个数 void (*Add)(ListArray *pList, void *pListPoint); //添加 void (*Remove)(ListArray *pList, void *pListPoint); //移除 void (*Delete)(void *pList); //析构};//List类的析构函数static void ListDelete(void *pList){ if(((ListArray *)pList)->pListPointArray != RT_NULL) //先释放指针数组 { rt_free(((ListArray *)pList)->pListPointArray); } rt_free(pList); //再释放整个List类}//元素增加函数static void ListAdd(ListArray *pList, void *pListPoint){ void **tListPointArray = rt_malloc(sizeof(int *) * (pList->Total + 1)); //申请比原来大一个存储单元的内存 int pListIndex; for(pListIndex = 0; pListIndex < pList->Total; pListIndex++) //拷贝 { if(pList->pListPointArray[pListIndex] == pListPoint) //判断,如果有相同的元素存在 { rt_free(tListPointArray); //释放现申请的内存 return; //返回 } tListPointArray[pListIndex] = pList->pListPointArray[pListIndex]; //拷贝 } tListPointArray[pList->Total] = pListPoint; //将添加的元素放到最后一个存储单元中 pList->Total += 1; //总数加1 if(pList->pListPointArray != RT_NULL) rt_free(pList->pListPointArray); //释放原来的内存 pList->pListPointArray = tListPointArray; //将新的句柄替换原句柄}//元素移除函数static void ListRemove(ListArray *pList, void *pListPoint){ int pListIndex, tListIndex; void **tListPointArray; void **FreePointArray; void **SavePointArray; if(pList->Total == 0) return; //总数为0时退出 tListPointArray = rt_malloc(sizeof(int) * (pList->Total - 1)); //申请比原来小一个存储单元的内存 FreePointArray = tListPointArray; //将刚申请的内存空间作为默认的释放空间 SavePointArray = pList->pListPointArray; //将已有的内存空间作为默认的存储空间 for(pListIndex = 0, tListIndex= 0; pListIndex < pList->Total; pListIndex++) //查找移除点 { if(pList->pListPointArray[pListIndex] == pListPoint) //当前点是移除点 { FreePointArray = pList->pListPointArray; //改变释放内存指针 SavePointArray = tListPointArray; //改变保留内存指针 continue; //结束本次循环 } if(tListIndex < (pList->Total -1)) //如果当前点不是移除点,拷贝序号小于总量减1 { tListPointArray[tListIndex] = pList->pListPointArray[pListIndex]; //拷贝 tListIndex++; //拷贝序号加1 } } pList->Total = (SavePointArray == tListPointArray) ? pList->Total - 1 : pList->Total; //根据保留的内存块改变总数的值 if(FreePointArray != RT_NULL) rt_free(FreePointArray); //释放该释放的不用的内存块 pList->pListPointArray = SavePointArray; //保留该保留的}//List构造函数static ListArray *ListCreate(void){ ListArray *pList = (ListArray *)rt_malloc(sizeof(ListArray)); pList->Total = 0; pList->pListPointArray = RT_NULL; pList->Add = ListAdd; pList->Remove = ListRemove; pList->Delete = ListDelete; return pList;}#endif此种方法是在添加或删除数组中的元素时,重新申请大1或者小1的一块内存,然后将原数组拷到新申请的内存中,然后将原来的数组指针替换掉!
一事不明关于main函数return 零
看起来像函数定义但没有参数列表;跳
使用typedef定义结构体解决思路
求教赋值有关问题
C中\t跟\n 的区别
pScanInfo-gt;last_file_path3的内容为啥
获得CPU电扇转速
char*和char[][]的有关问题
c语言中的关键字小结
malloc 有关问题 求解