设计简易的Vector数组main.c 12345678910111213141516#define _CRT_SECURE_NO_WARNINGS#include "Vector.h"int main(void) { Vector* v = create_vector(); if (!v) { printf("create_vector failed!\n"); exit(1); } for(int val = 0;val <= 99;val++) push_back(v, val); for (int i = 0; i < 100; i++) printf("%d\n", v->elements[i]); destroy_vector(v); return 0;} Vector.c 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#include "Vector.h"#define DEFAULT_CAPACITY 8#define THRESHOLD 1024Vector* create_vector() { //类似C++中的无参构造方法 Vector* v = malloc(sizeof(Vector)); if (!v) { return NULL; } v->capacity = DEFAULT_CAPACITY; v->elements = malloc(sizeof(int) * v->capacity); if (!v->elements) { free(v);// Caution: 一定要free(v) return NULL; } v->size = 0; return v;}void destroy_vector(Vector* v) { //类似C++里面的析构函数 free(v->elements); free(v);}void grow_capacity(Vector* v) { if (v->capacity <= THRESHOLD) { v->capacity += v->capacity; } else { v->capacity += (v->capacity >> 1); } int* result = realloc(v->elements, sizeof(int) * v->capacity); if (!result) { printf("grow_capacity failed!\n"); exit(1); } // 指向新的内存空间 v->elements = result; }void push_back(Vector* v, int val) { //先判断要不要扩容 if (v->size == v->capacity)//此时刚好满了 { grow_capacity(v); } v->elements[v->size++] = val; return;} Vector.h 1234567891011121314#include<stdlib.h>#include<stdio.h>//对外的接口:结构体的定义, APItypedef struct { int* elements; // 指向堆空间的数组 int size;//元素的个数 int capacity;//数组的容量}Vector ;Vector* create_vector();void destroy_vector(Vector* v);void push_back(Vector* v, int val);void grow_capacity(Vector* v);