.h
#ifndef DYAMIC_ARRAY_H
#define DYAMIC_ARRAY_H
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
1.动态增长内存——将数据存放在堆上。
2.数组空间可能会不够
3.capacity 容量。
4.size 当前数据个数。
*/
typedef struct DYAMICARRAY
{
int *pAddr;
int size;
int capacity;
}Dynamic_Array;
//操作函数
//初始化
Dynamic_Array * Init_Array();
//插入
void Push_back_Array(Dynamic_Array *arr, int val);
//删除
void RemoveByPos_Array(Dynamic_Array *arr, int pos);
void RemoveByValue_Array(Dynamic_Array *arr, int value);
//查找
int Find_ByValue(Dynamic_Array *arr, int value);
//遍历
void Print_Array(Dynamic_Array *arr);
//释放空间
void FreeSpace_Array(Dynamic_Array *arr);
void Clear_Arrray(Dynamic_Array *arr);
//参数获取
int Capacity_Array(Dynamic_Array *arr);
int Size_Array(Dynamic_Array *arr);
int At_Array(Dynamic_Array *arr, int pos);
#endif
.c
#include "DynamicArray.h"
//初始化
Dynamic_Array * Init_Array()
{
Dynamic_Array * MyArray = (Dynamic_Array *)malloc(sizeof(Dynamic_Array));
MyArray->capacity = 20;
MyArray->size = 0;
MyArray->pAddr = (int*)malloc(sizeof(int)*(MyArray->capacity));
return MyArray;
}
//插入
void Push_back_Array(Dynamic_Array *arr, int val)
{
if (arr == NULL)
{
return;
}
//判断空间师傅足够
if (arr->size == arr->capacity)
{
int * NewSpace = (int*)malloc(sizeof(int)*arr->capacity * 2);
//拷贝数据
memcpy(NewSpace, arr->pAddr, arr->capacity);
free(arr->pAddr);
//更新空间和容量
arr->pAddr = NewSpace;
arr->capacity = arr->capacity * 2;
}
//插入数据
arr->pAddr[arr->size] = val;
arr->size++;
}
//删除
void RemoveByPos_Array(Dynamic_Array *arr, int pos)
{
if (arr == NULL)
{
return ;
}
if (pos < 0 || pos>arr->size)
{
return ;
}
for (int i = pos; i < arr->size; i++)
{
arr->pAddr[i] = arr->pAddr[i + 1];
}
}
void RemoveByValue_Array(Dynamic_Array *arr, int value)
{
if (arr == NULL)
{
return ;
}
int pos = Find_ByValue( arr, value);
for (int i = 0; i < arr->size; i++)
{
if (arr->pAddr[i] == value)
{
pos = i;
break;
}
}
RemoveByPos_Array(arr, pos);
}
//查找
int Find_ByValue(Dynamic_Array *arr, int value)
{
if (arr == NULL)
{
return -1;
}
int pos = -1;
for (int i = 0; i < arr->size; i++)
{
if (arr->pAddr[i] == value)
{
pos = i;
break;
}
}
return arr->pAddr[pos];
}
//遍历
void Print_Array(Dynamic_Array *arr)
{
for (int i = 0; i < arr->size; i++)
{
printf(" %d", arr->pAddr[i]);
}
printf("\n");
}
//释放空间
void FreeSpace_Array(Dynamic_Array *arr)
{
if (arr == NULL)
{
return;
}
if (arr->pAddr != NULL)
{
free(arr->pAddr);
}
free(arr);
}
//清空
void Clear_Arrray(Dynamic_Array *arr)
{
if (arr == NULL)
{
return;
}
arr->size = 0;
}
//返回参数
int Capacity_Array(Dynamic_Array *arr)
{
if (arr == NULL)
{
return -1;
}
return arr->capacity;
}
int Size_Array(Dynamic_Array *arr)
{
if (arr == NULL)
{
return 0;
}
return arr->size;
}
int At_Array(Dynamic_Array *arr, int pos)
{
return arr->pAddr[pos];
}