English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C에서 realloc() 사용

realloc 함수는 malloc 또는 calloc으로 할당된 이전 메모리 블록의 크기를 조정하는 데 사용됩니다.

이것은 C 언어에서 realloc의 문법입니다

void *realloc(void *pointer, size_t size)

여기서는

포인터-malloc 또는 calloc을 통해 이전에 할당된 메모리 블록을 가리키는 포인터

크기-메모리 블록의 새 크기입니다。

이것은realloc()C 언어의 예제

예제

#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("\n오류! 메모리가 할당되지 않았습니다.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\n합: %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("\n합: %d", s);
   return 0;
}

출력 결과

배열의 요소를 입력하세요: 3 34 28 8
합: 73
배열의 요소를 입력하세요: 3 28 33 8 10 15
합: 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);
}