c语言动态数组的实现以及相关增删的功能的实现

时间:2025-02-14 13:16:47
  • #include<>
  • #include<>
  • #include<>
  • #define start_capacity 5
  • #define plus_capacity 5
  • typedef struct x
  • {
  • void** ptr;
  • int capacity;
  • int num;
  • }D_array;
  • D_array* inti_data(int capacity)//初始化动态数组
  • {
  • D_array* array = (D_array*)malloc(sizeof(D_array));
  • if (array == NULL)
  • return NULL;
  • array->ptr = (void**)malloc(sizeof(void*) * capacity);
  • if (array->ptr == NULL)
  • return NULL;
  • array->capacity = capacity;
  • array->num = 0;
  • return array;
  • }
  • void insert_data(D_array* array, int pos, void* data)
  • {
  • if (pos < 0)
  • {
  • printf("位置错误\n");
  • return;
  • }
  • if (data == NULL)
  • return;
  • if (array->capacity == array->num)//扩容
  • {
  • int newcapacity = array->capacity + plus_capacity;
  • void** newspace = (void**)malloc(sizeof(void*) * newcapacity);
  • if (newspace == NULL)
  • {
  • printf("扩容失败\n");
  • return;
  • }
  • memcpy(newspace, array->ptr, sizeof(void*) * array->capacity);
  • free(array->ptr);
  • array->ptr = newspace;
  • array->capacity = newcapacity;
  • printf("扩容成功\n");
  • }
  • //末尾插入
  • if (pos > array->num)
  • {
  • pos = array->num;
  • }
  • //不是尾插就要移动
  • for (int i = array->num - 1; i >= pos; i--)
  • {
  • array->ptr[i + 1] = array->ptr[i];
  • }
  • //指定位置插入
  • memcpy(array->ptr + pos, &data, 4);
  • array->num++;
  • }
  • void userprint(void *p)//用户根据需要来自定义数据类型
  • {
  • int* p1 = (int*)p;
  • printf("%d ", *p1);
  • }
  • void foreach(D_array* array)//动态数组的遍历
  • {
  • for (int i = 0; i < array->num; i++)
  • {
  • userprint(array->ptr[i]);
  • }
  • printf("\n");
  • }
  • //数据的删除
  • void del_data(D_array *array,int pos)
  • {
  • if (pos >= array->num)
  • return;
  • for (int i = pos; i < array->num - 1; i++)
  • {
  • array->ptr[i] = array->ptr[i + 1];
  • }
  • array->num--;
  • }
  • void destroy(D_array* array)
  • {
  • free(array->ptr);
  • array->ptr = NULL;
  • array->num = 0;
  • array->capacity = 0;
  • }
  • int main()
  • {
  • D_array* array= inti_data(start_capacity);
  • //测试初始化数组:
  • //printf("%d %d",array->capacity,array->num);
  • //测试扩容和插入
  • int p1 = 3;
  • int p2 = 5;
  • int p3 = 4;
  • insert_data(array, 4, &p1);
  • insert_data(array, 0, &p2);
  • insert_data(array, 2, &p3);
  • foreach(array);
  • printf("%d %d\n", array->capacity, array->num);
  • del_data(array, 1);
  • foreach(array);
  • printf("%d %d\n", array->capacity, array->num);
  • destroy(array);
  • printf("%d %d\n", array->capacity, array->num);
  • }
  • 相关文章