1. 头文件DynamicArray.h
#ifndef DYNAMIC_ARRAY_H
#define DYNAMIC_ARRAY_H
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
typedef struct DYNAMICARRAY {
int* pAddr;
int size;
int capacity;
}Dynamic_Array;
Dynamic_Array* Init_Array();
void PushBack_Array(Dynamic_Array* arr, int value);
void RemoveByPos_Array(Dynamic_Array* arr, int pos);
void RemoveByValue_Array(Dynamic_Array* arr, int value);
int Find_Array(Dynamic_Array* arr, int value);
void Print_Array(Dynamic_Array* arr);
void FreeSpace_Array(Dynamic_Array* arr);
void Clear_Array(Dynamic_Array* arr);
int Capacity_Array(Dynamic_Array* arr);
int Size_Array(Dynamic_Array* arr);
int At_Array(Dynamic_Array * arr,int pos);
#endif
2. 实现函数 DynamicArray.c
#include "DynamicArray.h"
#include<iostream>
using namespace std;
Dynamic_Array* Init_Array() {
Dynamic_Array* myArray = (Dynamic_Array*)malloc(sizeof(Dynamic_Array));
myArray->size = 0;
myArray->capacity = 20;
myArray->pAddr = (int*)malloc(sizeof(int) * myArray->capacity);
return myArray;
}
void PushBack_Array(Dynamic_Array* arr, int value) {
if (arr == NULL) return;
if (arr->size == arr->capacity) {
int* newSpace = (int*)malloc(sizeof(int) * arr->capacity * 2);
memcpy(newSpace, arr->pAddr, arr->capacity * sizeof(int));
free(arr->pAddr);
arr->capacity = arr->capacity * 2;
arr->pAddr = newSpace;
}
arr->pAddr[arr->size] = value;
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];
}
arr->size--;
}
void RemoveByValue_Array(Dynamic_Array* arr, int value) {
if (arr == NULL) return;
int pos = Find_Array(arr,value);
RemoveByPos_Array(arr, pos);
}
int Find_Array(Dynamic_Array* arr, int value)
{
if (arr == NULL) return -1;
int pos = -1;
for (int i = 0; i < arr->size; i++)
{
if (value == arr->pAddr[i]) {
pos = i;
break;
}
}
return pos;
}
void Print_Array(Dynamic_Array* arr) {
if (arr == NULL) return;
for (int i=0; i < arr->size; i++)
{
cout << arr->pAddr[i]<<" ";
}
cout << endl;
}
void FreeSpace_Array(Dynamic_Array* arr) {
if (arr == NULL)
{
return;
}
if (arr->pAddr != NULL) {
free(arr->pAddr);
}
free(arr);
}
void Clear_Array(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 -1;
return arr->size;
}
int At_Array(Dynamic_Array* arr, int pos)
{
if (arr == NULL) return -1;
return arr->pAddr[pos];
}
3. 主函数
#define _CRT_SECURE_NO_WARNINGs
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<iostream>
#include"DynamicArray.h"
using namespace std;
void test() {
Dynamic_Array* myArryay = Init_Array();
for (int i = 0; i < 10; i++) {
PushBack_Array(myArryay, i);
}
cout<<Find_Array(myArryay, 6);
PushBack_Array(myArryay, 11);
Print_Array(myArryay);
cout<<Capacity_Array(myArryay);
}
int main(void) {
test();
system("pause");
return 0;
}