본문 바로가기
컴퓨터/프로그래밍 언어

[C언어] malloc 으로 2차원 동적 배열을 할당하는 방법

by Luyin 2012. 7. 19.

malloc 으로 1차원 배열을 할당하는건 쉽다.

int input;

scanf("%d", &input);

이 있고, input받은 숫자를 크기로 가지는 array 배열을 만들 때

int *array = (int *)malloc(sizeof(int)*input);

로 넣으면 된다.

하지만 2차원 배열을 생성하려면 조금 생각해야한다.

input*input 크기를 가지는 2차원 array 배열을 만들려면 방법을 모르는사람(나같은경우...)은 이렇게 생각할 수 있다.

int **array = (int **)malloc(sizeof(int)*input*input);

컴파일러는 친절하게 에러를 표시한다 :D

그럼 어떻게 생성해야할까?

포인터를 두번쓰는건 맞다. 만들려는 배열이 2차원이니 대표주소를 가르키기 위해선 포인터를 2개 써야한다.

하지만 포인터를 두번 쓰는것만으로는 2차원배열을 모두 할당할 수는 없다.

이럴때는 2차원배열에 대해서 한번 malloc 으로 동적생성해주고 생성된 배열에 대해서 malloc으로 배열을 한번 더 생성해주면 된다.

이말이 무슨말이냐...

int **array = (int**)malloc(sizeof(int *)*input);

로 한번 생성해주고 input이 3이라고 가정하면 int형 배열 *array[0], *array[1], *array[2] 이렇게 3개가 생성된다.

이 각각의 배열에 대해서 또 malloc을 지정해주면 동적 할당이 되는것이다. 즉

array[0] = (int *)malloc(sizeof(int)*input);

array[1] = (int *)malloc(sizeof(int)*input);

array[2] = (int *)malloc(sizeof(int)*input);

=

for(int i=0; i<input; i++)

array[i] = (int *)malloc(sizeof(int)*input);

를 넣어주면 되는것이다.

여기서 sizeof(int *) 의 의미를 물어볼 수 있는데..

이렇게 일차적으로 동적배열을 할당해주기는 하지만 사실 두번째 동적배열을 할당할 때 크기를 몇으로 가지는지 컴파일러가 알 수 없기 때문에 일단 포인터형으로 크기를 지정해놓았다. 즉 int **array = (int**)malloc(sizeof(int *)*input); 이것만 지정해서는 array의 배열 크기를 알 수 없다는 뜻이다.

2차원배열 생성 코드를 정리해놓으면

int input, i;

scanf("%d", &input);

int **array = (int**)malloc(sizeof(int *)*input);

for(i=0; i<input; i++)

array[i] = (int *)malloc(sizeof(int)*input);

생성된 array[input][input] 을 사용

for(i=0; i<input; i++)

free(array[i]);
free(array);

이렇게 된다.

동적배열을 1차원간격으로 나누어서 정의하였으니 free도 나누어서 해주어야 한다.