[[사외교육]]/[SDS]신입사원_역량강화

realloc() 의 사용 예제

갑빠돌격기 2011. 3. 7. 12:57

//CreateArray()에서 생성된 DArray->array의 사이즈 보다
//더 큰 배열을 요구하였을때 (예제에서는 2배)
//AddArray()에서 realloc()을 이용하여
//해당 구조체에 매달린 배열을 동적으로 생성하는 예제 코드.

#include<stdio.h>
#include<stdlib.h>

/* 생성될 array 의 정보를 담고 있는 구조체*/
typedef struct DArray{
        int max_size; //현재 최대 크기
        int size;        // 현재 위치
        int* array;    //배열 시작주소
}DArray;

//초기 사용자로부터 [5]크기를 가진 배열의 생성 및 초기화 함수
DArray* CreateArray()
{
        DArray* temp=(DArray*)malloc(sizeof(DArray));

        temp->max_size = 5;
        temp->size=0;
        temp->array = (int*)malloc(sizeof(int)*(temp->max_size));
        return temp;
}

/* 구조체 및 매달린 배열을 free해주는 디스토리 함수 */
void DestoryArray(DArray* lpArray)
{
        free(lpArray->array);
        free(lpArray);
}

/* 구조체에 매달린 배열의 크기를 동적으로(예제에서는 2배만큼) 변경하여 주는 함수 */
void AddArray(DArray* lpArray , int value)
{
        if(lpArray->size == lpArray->max_size)  //full
        {
                lpArray->array = (int*)realloc(lpArray->array , (sizeof(int)*(lpArray->max_size*2)));
        }
        if(lpArray->array==NULL)
        {
                perror("Memory Realloc");
                exit(1);
        }
        lpArray->max_size *=2;
        lpArray->array[lpArray->size++] = value;
}

/* main에서의 value값을 변경시켜 주는 함수
void PrintArray(DArray* lpArray , int i , int * value)
{
        *value = (lpArray->array)[i];
}

int main()
{
        int value;
        int i;
        DArray* lpArray;
        int array_size=20;


        lpArray = CreateArray();        //배열 선언 

        for(i=0 ; i<array_size ; i++)
        {
                AddArray(lpArray ,  i);
        }


        for(i=0; i<array_size ; i++)
        {
                PrintArray(lpArray , i , &value);
                printf("%d\n" , value);
        }

        //DestoryArray(lpArray);

        return 0;
}