动态数组设计
struct dynamicArray
{
void** pAddr; //维护真实在堆区创建的数组的指针
int m_capacity; //数组容量
int m_size; // 数组大小
};
数组初始化
struct dynamicArray * init_DynamicArry(int capacity)
{
if (capacity <= 0)
{
return NULL;
}
//给数组分配空间
struct dynamicArray * array = malloc(sizeof(struct dynamicArray));
if (array == NULL)
{
return NULL;
}
array->pAddr = malloc(sizeof(void * ) * capacity);
array->m_capacity = capacity;
array->m_size = 0;
return array;
}
插入数组
void insert_DynamicArray(struct dynamicArray* array, int pos, void* data)
{
if (array == NULL)
{
return;
}
if (data == NULL)
{
return;
}
//无效位置 尾插
if(pos < 0 || pos > array->m_size)
{
pos = array->m_size;
}
//判断是否满了,满了就动态扩展
if (array->m_size == array->m_capacity)
{
// 申请更大空间
int newCapacity = array->m_capacity * 2;
// 创建新空间
void ** newSpace = malloc(sizeof(void*) * newCapacity);
//将原有数据拷贝到新空间下
memcpy(newSpace, array->pAddr, sizeof(void*) * array->m_capacity);
//释放原有内存
free(array->pAddr);
//更新新空间指向
array->pAddr = newSpace;
//更新新容量
array->m_capacity = newCapacity;
}
//插入新元素
//移动元素 进行插入新元素
for (int i = array->m_size -1; i >= pos; i--)
{
// 数据向后移动
array->pAddr[i + 1] = array->pAddr[i];
}
// 将新元素插入到指定位置上
array->pAddr[pos] = data;
//更新大小
array->m_size++;
}
遍历数组
void foreach_DynamicArray(struct dynamicArray* array, void (*myPrint)(void*))
{
if (array == NULL)
{
return;
}
if (myPrint == NULL)
{
return;
}
for (int i = 0; i < array->m_size; i++)
{
myPrint(array->pAddr[i]);
}
}
标签:动态,capacity,int,void,pAddr,数组,array,数据结构,size
From: https://www.cnblogs.com/ffff5/p/18323708