600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 游戏筑基开发之动态数组(C语言)

游戏筑基开发之动态数组(C语言)

时间:2022-12-19 07:43:24

相关推荐

游戏筑基开发之动态数组(C语言)

利用结构体以及指针的相关知识创建动态整型数组

主要功能包括:初始化动态数组、释放动态数组、插入数据在动态数组尾部、指定下标删除数据(从0开始)、指定下标更新数据、打印动态数组等。

该动态数组根据将根据使用者动态扩容。初始大小:10个整型大小。

数据结构如下:

// 动态数组typedef struct tagVector{int* pArr;//存储数据int nLen;//当前长度int nLenMax;//最大长度}TVector, *PTVector;

具体实现如下:

#include <stdio.h>#include <memory.h>// 动态数组typedef struct tagVector{int* pArr;int nLen;int nLenMax;}TVector, *PTVector;// 初始化动态数组static int VectorInit(PTVector* ppv){// 创建一个结构体,在堆区PTVector pv = malloc(sizeof(TVector));//PTVector pv = malloc(sizeof(TVector));pv->nLen = 0;pv->nLenMax = 10;// 申请一个长度为pv->nLenMax的int内存空间pv->pArr = malloc(sizeof(int) * pv->nLenMax);// 返回创建的动态数组结构体*ppv = pv;return 1;}// 释放指针static int VectorFree(PTVector *ppv){//free(pv);pv = NULL;if (*ppv == NULL)return 0;free((*ppv)->pArr);free(*ppv);*ppv = NULL;return 1;}// 插入数据在尾部static int VectorInsert(PTVector pv,int data){if (pv == NULL)return 0;if (pv->nLen + 1 == pv->nLenMax){pv->nLenMax *= 5;int *temp = malloc(sizeof(int)*(pv->nLenMax));memcpy(temp, pv->pArr, sizeof(int)*((pv->nLenMax)/5));//无条件复制free(pv->pArr);pv->pArr = temp;temp = NULL;}/*(*(pv->pArr + pv->nLen)) = data;pv->nLen++;*/(pv->pArr)[pv->nLen++] = data;return 1;}// 删除指定下标static int VectorDelete(PTVector pv,int index){if (pv == NULL || pv->nLen < index + 1)return 0;for (int i = index; i < pv->nLenMax - 2; i++)pv->pArr[i] = pv->pArr[i + 1];pv->nLenMax--;}// 更新指定下标数据static int VectorUpdate(PTVector pv, int index,int data){if (pv == NULL || pv->nLen < index + 1)return 0;pv->pArr[index] = data;return 1;}// 打印数据static void VectorPrint(PTVector pv){for (int i = 0; i < pv->nLen; i++)printf("%3d", pv->pArr[i]);printf("\n");}int main(){PTVector pv = NULL;VectorInit(&pv);//传入二级指针int count = 0;//测试用例while (1){VectorInsert(pv, 6 + count);if ((count++) == 12)break;}VectorPrint(pv);printf("\n");VectorUpdate(pv, 4, 100);VectorPrint(pv);return 0;}

关于mencpy的详情介绍【点击跳转】

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。