관리 메뉴

DREAM IT, WISH IT, DO IT

[C - 동적배열] 메모리 재할당을 통한 동적배열 본문

Programming/C/C++

[C - 동적배열] 메모리 재할당을 통한 동적배열

개발일지 오세빈 2012. 1. 26. 09:35

#include stdio.h
#include string.h
#include stdlib.h

#define ELETYPE int
ELETYPE *ar;
unsigned size;
unsigned num;
unsigned growby;

void InitArray(unsigned asize, unsigned agrowby)
{
	size = asize;
	growby = agrowby;
	num = 0;
	ar = (ELETYPE *)malloc(size * sizeof(ELETYPE));
}

void Insert(int index, ELETYPE value)
{
	unsigned need;
	
	need = num + 1;
	if (need > size) {
		size = need + growby;
		ar = (ELETYPE *)realloc(ar, size * sizeof(ELETYPE));
	}
	memmove(ar + index + 1, ar + index, (num - index) * sizeof(ELETYPE));
	ar[index] = value;
	num++;
}

void Delete(int index)
{
	memmove(ar + index, ar + index + 1, (num - index - 1)*sizeof(ELETYPE));
	num--;
}

void Append(ELETYPE value)
{
	Insert(num, value);
}

void UnInitArray()
{
	free(ar);
}

void DumpArray(char* sMark)
{
	unsigned i;
	printf("%16s => Size = %02d, Count = %02d : ", sMark, size, num);
	for (i = 0; i < num; i++) {
		printf("%2d ",ar[i]);
	}
	printf("\n");
}

int main()
{
	int i;
	
	InitArray(10, 5);
	DumpArray("First");
	
	for (i = 0; i <= 8; i++) {
		Append(i);
	}
	DumpArray("Append 8 => ");
	
	Insert(5, 5);
	DumpArray("Insert 10 => ");
	Insert(5, 5);
	DumpArray("Insert 11 => ");
	Insert(5, 5);
	DumpArray("Insert 12 => ");
	
	Delete(7);
	DumpArray("Delete index 7 => ");
	
	UnInitArray();
	
	return 0;
}
0 Comments
댓글쓰기 폼