realloc 함수는 이전에 malloc 또는 calloc에 의해 할당된 메모리 블록의 크기를 조정하는 데 사용됩니다.
다음은 C 언어의 realloc 구문입니다.
void *realloc(void *pointer, size_t size)
여기,
포인터 − malloc 또는 calloc에 의해 이전에 할당된 메모리 블록을 가리키는 포인터.
크기 - 메모리 블록의 새로운 크기.
다음은 C 언어로 된 realloc()의 예입니다.
예
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
return 0;
} 출력
Enter elements of array : 3 34 28 8 Sum : 73 Enter elements of array : 3 28 33 8 10 15 Sum : 145
위의 프로그램에서 메모리 블록은 calloc()에 의해 할당되고 요소의 합이 계산됩니다. 그 후, realloc()은 메모리 블록의 크기를 4에서 6으로 조정하고 합을 계산합니다.
p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}