#include <stdio.h>
#include <stdlib.h>
void main()
{
int i, j;
int nRow=5, nCol=4;
int **aNum;
// 유동 할당하기
aNum = (int **)malloc(nRow * sizeof(int *));
for(i=0; i<nRow; ++i)
{
aNum[i] = (int *)malloc( nCol * sizeof(int) );
for(j=0; j<nCol; ++j) aNum[i][j] = 0;
}
// 결과 출력하기
for(i=0; i<nRow; ++i)
{
for(j=0; j<nCol; ++j) printf("%d", aNum[i][j]);
printf("\n");
}
// 할당 해제하기
for(i=0; i<nRow; ++i) free(aNum[i]);
free(aNum);
}실행하면 다음처럼 결과가 출력된다.
0000
0000
0000
0000
0000
malloc() 대신 calloc()를 써서 위와 똑같은 결과를 낼 수 있다.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i, j;
int nRow=5, nCol=4;
int **aNum;
// 메모리 할당하기
aNum = (int **)calloc(nRow, sizeof(int *));
for(i=0; i<nRow; ++i)
{
aNum[i] = (int *)calloc( nCol, sizeof(int) );
}
// 결과 출력하기
for(i=0; i<nRow; ++i)
{
for(j=0; j<nCol; ++j) printf("%d", aNum[i][j]);
printf("\n");
}
// 할당 해제하기
for(i=0; i<nRow; ++i) free(aNum[i]);
free(aNum);
}0을 대입하는 구문이 빠진 이유는 calloc()가 할당한 공간의 값을 0(null)으로 채워서 굳이 필요하지 않기 때문이다.