动态数组进行插入查找时出现 Warning C6386 Buffer overrun while writing to 'array->pAddr'.
但是结果没有影响
typedef struct DynamicArray
{
void** pAddr;
int m_capacity;
int m_size;
}DynamicArray;
//初始化数组
DynamicArray* init_array(int capacity)
{
if (capacity == 0)
{
return NULL;
}
DynamicArray* array = (DynamicArray*)malloc(sizeof(DynamicArray));
if (array == 0)
{
return NULL;
}
array->pAddr = (void**)malloc(sizeof(void*) * capacity);
if (array->pAddr == NULL)
{
perror("init_array");
return NULL;
}
array->m_size = 0;
array->m_capacity = capacity;
return array;
}
void insert_array(DynamicArray* array, int pos, void* data)
{
if (array == NULL)
{
return;
}
if (data == NULL)
{
return;
}
//输入的位置大于现有的size
if (pos > array->m_size)
{
pos = array->m_size;
}
//无效位置 尾插
if (pos < 0 || pos > array->m_size)
{
pos = array->m_size;
}
//如果内存不够扩容
if (array->m_size == array->m_capacity)
{
//1 计算新空间大小
int newCapacity = array->m_capacity * 2;
//2 创建新空间
void** newSpace = malloc(sizeof(void*) * newCapacity);
if (newSpace == NULL)
{
return;
}
//3 将原有数据拷贝
memcpy(newSpace, array->pAddr, sizeof(void*) * array->m_capacity);
//4 释放原有内存空间
free(array->pAddr);
//5 更新空间指向
array->pAddr = newSpace;
//6 更新容量
array->m_capacity = newCapacity;
}
for (int i = array->m_size - 1; i >= pos; i--)
{
//向后移动
array->pAddr[i + 1] = array->pAddr[i]; //这行报错 c6836 buffer overn while writing "array->pAddr "
}
//插入指定位置
array->pAddr[pos] = data;
array->m_size++;
}