>  기사  >  백엔드 개발  >  C 언어에서 Realloc은 무엇을 의미합니까?

C 언어에서 Realloc은 무엇을 의미합니까?

WBOY
WBOY앞으로
2023-08-28 12:41:051296검색

C 라이브러리의 메모리 할당 함수 void *realloc(void *ptr, size_t size)는 이전에 malloc 또는 calloc 호출을 사용하여 할당되었던 ptr이 가리키는 메모리 블록의 크기를 조정하려고 시도합니다.

메모리 할당 기능

메모리는 두 가지 방법으로 할당할 수 있습니다.

C 언어에서 Realloc은 무엇을 의미합니까?

컴파일 시 메모리가 할당되면 실행 중에 변경할 수 없습니다. 메모리가 부족하거나 메모리 낭비입니다.

해결책은 실행 중 프로그램의 필요에 따라 동적으로 메모리를 생성하는 것입니다.

동적 메모리 관리를 위한 표준 라이브러리 함수는 다음과 같습니다.

  • malloc( )
  • calloc( )
  • realloc( )
  • free( )

realloc( ) 함수

  • 는 재할당에 사용됩니다. 할당된 메모리.

  • 할당된 메모리를 줄이거나 늘릴 수 있습니다.

  • 재할당된 메모리의 기본 주소를 가리키는 void 포인터를 반환합니다.

realloc() 함수의 구문은 다음과 같습니다.

Free void *realloc (pointer, newsize);

Example

다음 예제에서는 realloc() 함수의 사용법을 보여줍니다.

int *ptr;
ptr = (int * ) malloc (1000);// we can use calloc also
- - -
- - -
- - -
ptr = (int * ) realloc (ptr, 500);
- - -
- - -
ptr = (int * ) realloc (ptr, 1500);

예제

다음은 realloc() 함수를 사용한 C 프로그램입니다.

Online Demonstration

#include<stdio.h>
#include<stdlib.h>
int main(){
   int *ptr, i, num;
   printf("array size is 5</p><p>");
   ptr = (int*)calloc(5, sizeof(int));
   if(ptr==NULL){
      printf("Memory allocation failed");
      exit(1); // exit the program
   }
   for(i = 0; i < 5; i++){
      printf("enter number at %d: ", i);
      scanf("%d", ptr+i);
   }
   printf("</p><p>Let&#39;s increase the array size to 7</p><p> ");
   ptr = (int*)realloc(ptr, 7 * sizeof(int));
   if(ptr==NULL){
      printf("Memory allocation failed");
      exit(1); // exit the program
   }
   printf("</p><p> enter 2 more integers</p><p></p><p>");
   for(i = 5; i < 7; i++){
      printf("Enter element number at %d: ", i);
      scanf("%d", ptr+i);
   }
   printf("</p><p> result array is: </p><p></p><p>");
   for(i = 0; i < 7; i++){
      printf("%d ", *(ptr+i) );
   }
   return 0;
}

Output

위 프로그램을 실행하면 다음과 같은 결과가 나옵니다 −

array size is 5
enter number at 0: 23
enter number at 1: 12
enter number at 2: 45
enter number at 3: 67
enter number at 4: 20
Let&#39;s increase the array size to 7
enter 2 more integers
Enter element number at 5: 90
Enter element number at 6: 60
result array is:
23 12 45 67 20 90 60

위 내용은 C 언어에서 Realloc은 무엇을 의미합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제