顺序表(动态分配) – 增加动态数组的长度

  • Post author:
  • Post category:其他


#include <stdio.h>
#include <stdlib.h>
#define InitSize 10

typedef struct
{
	ElemType *data;
	int MaxSize;
	int length;
} SqList;

//初始化
void InitList(SqList &L)
{
	L.data = (int *)malloc(InitSize*sizeof(int));
	L.length = 0;
	L.MaxSize = InitSize;
}

//增加动态数组的长度
void IncreaseSize(SqList &L, int len)
{
	int *p = L.data;
	L.data = (int *)malloc((L.MaxSize+len)*sizeof(int));
	for ( int i = 0; i < L.length; i++ )
		L.data[i] = p[i];	//将数据复制到新区域
	L.MaxSize = L.MaxSize+len;
	free(p);
}

int main(void)
{
	SqList L;
	InitList(L);
	//...
	IncreaseSize(L,5);
	return 0;
}



版权声明:本文为XING_Gou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。