数组结构定义
struct DynamicArray
{
void** arr;
int m_nCapacity;
int m_nSize;
};
实现
#include<stdlib.h>
#include<string.h>
//initial array
struct DynamicArray* init_DynamicArray(int nCapacity)
{
struct DynamicArray* pMyArr = (struct DynamicArray*)malloc(sizeof(struct DynamicArray));
if (NULL == pMyArr)
{
return NULL;
}
pMyArr->arr = (void**)malloc(sizeof(void*)*nCapacity);
pMyArr->m_nCapacity = nCapacity;
pMyArr->m_nSize = 0;
return pMyArr;
}
//insert item
void insert_DynamicArray(struct DynamicArray* pList,int pos,void* data)
{
if (NULL == pList)
{
return;
}
if (NULL == data)
{
return;
}
//无效位置 强制尾插
if (pos < 0 || pos > pList->m_nSize)
{
pos = pList->m_nSize;
}
//扩容
if (pList->m_nSize == pList->m_nCapacity)
{
int nNewCapacity = pList->m_nCapacity*2;
void** pArr = (void**)malloc(sizeof(void*)*nNewCapacity);
memcpy(pArr,pList->arr,sizeof(void*)*pList->m_nSize);//注意拷贝内存大小
free(pList->arr);
pList->arr = pArr;
pList->m_nCapacity = nNewCapacity;//更新容量
}
//insert 向后移位
for(int i = pList->m_nSize-1;i>=pos;i--)
{
pList->arr[i+1] = pList->arr[i];
}
pList->arr[pos] = data;
pList->m_nSize++;//更新大小
}
//遍历数组
void visit_DynamicArray(struct DynamicArray* pList,void (*Print)(void*))
{
if(NULL == pList)
{
return;
}
for(int i=0;i<pList->m_nSize;++i)
{
Print(pList->arr[i]);
}
}
//删除元素
void deleteItem_DynamicArray(struct DynamicArray* pList,int pos)
{
if(NULL == pList)
{
return;
}
//无效位置直接返回
if (pos <0 || pos >= pList->m_nSize)
{
return;
}
//向前移位 覆盖pos处的值
for(int i=pos;i<pList->m_nSize-1;i++)
{
pList->arr[i] = pList->arr[i+1];
}
//数组大小减1
pList->m_nSize--;
}
//销毁数组
void destroy_DynamicArray(struct DynamicArray* pList)
{
if (NULL == pList)
{
return;
}
free(pList->arr);
free(pList);
pList == NULL;
}
test代码
struct Person
{
void* data;
char name[64];
int nAge;
};
void MyPrint(void* data)
{
Person* person = (Person*)data;
printf("name:%s,age:%d\n",person->name,person->nAge);
}
struct Person p1 = {NULL,"张三",12};
struct Person p2 = {NULL,"李四",15};
struct Person p3 = {NULL,"王麻子",18};
struct Person p4 = {NULL,"张五",19};
struct Person p5 = {NULL,"张飞",22};
//dynamic array
struct DynamicArray* pArray = init_DynamicArray(2);
printf("insert before:capacity=%d,size=%d\n",pArray->m_nCapacity,pArray->m_nSize);
insert_DynamicArray(pArray,0,&p1);
insert_DynamicArray(pArray,2,&p2);
insert_DynamicArray(pArray,-1,&p3);
insert_DynamicArray(pArray,5,&p4);
insert_DynamicArray(pArray,0,&p5);
printf("insert after:capacity=%d,size=%d\n",pArray->m_nCapacity,pArray->m_nSize);
visit_DynamicArray(pArray,MyPrint);
deleteItem_DynamicArray(pArray,4);
printf("delete after:capacity=%d,size=%d\n",pArray->m_nCapacity,pArray->m_nSize);
visit_DynamicArray(pArray,MyPrint);
destroy_DynamicArray(pArray);
printf("-------------------------------------\n");
测试结果