C calloc() 요소 크기 지정 동적 메모리 할당 함수
malloc() 함수처럼 메모리를 동적으로 할당받습니다. malloc() 함수가 바이트 단위로 메모리를 요청한다면 특정 크기에 대한 개수만큼을 메모리로 요청할 수 있습니다. 예제를 참고하세요.
- 헤더: stdlib.h
- 형태: void *calloc(size_t nelem, size_t elsize)
- 인수: size_t nelem 필요한 요소의 개수
size_t elsize 요소의 크기 - 반환: void * 할당된 메모리 포인터, 메모리 할당에 실패하면 NULL 반환
C언어 calloc() 함수 예제
#include <stdio.h>
#include <stdlib.h>
int main( void)
{
int *ptr_int1;
int *ptr_int2;
int ndx;
ptr_int1 = (int *)malloc( 50 *sizeof( int));
ptr_int2 = (int *)calloc( 50, sizeof( int));
for ( ndx= 0; ndx < 50; ndx++)
{
ptr_int1[ndx] = 2007 +ndx;
ptr_int2[ndx] = 2007 +ndx;
}
for ( ndx= 0; ndx < 50; ndx++)
{
printf( "%d %d\n", ptr_int1[ndx], ptr_int2[ndx]);
}
free( ptr_int1);
free( ptr_int2);
return 0;
}
C언어 calloc() 예제 실행 결과
]$ ./a.out
2007 2007
2008 2008
2009 2009
2010 2010
2011 2011
2012 2012
중략
2051 2051
2052 2052
2053 2053
2054 2054
2055 2055
2056 2056
]$
'컴퓨터 > 프로그래밍' 카테고리의 다른 글
C언어 free 함수 할당받은 메모리를 반환 (0) | 2020.03.12 |
---|---|
C언어 malloc 함수 동적 메모리 할당 (0) | 2020.03.12 |
C언어 strtof 함수 실수 문자열을 float형 실수로 변환 (0) | 2020.03.12 |