산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C 동적 메모리 할당

C 동적 메모리 할당

이 튜토리얼에서는 표준 라이브러리 함수인 malloc(), calloc(), free() 및 realloc()을 사용하여 C 프로그램에서 동적으로 메모리를 할당하는 방법을 배웁니다.

아시다시피 배열은 고정된 수의 값 모음입니다. 배열의 크기는 한 번 선언되면 변경할 수 없습니다.

때로는 선언한 배열의 크기가 충분하지 않을 수 있습니다. 이 문제를 해결하기 위해 런타임 중에 메모리를 수동으로 할당할 수 있습니다. 이것을 C 프로그래밍에서 동적 메모리 할당이라고 합니다.

메모리를 동적으로 할당하려면 라이브러리 함수는 malloc()입니다. , calloc() , realloc()free() 사용됩니다. 이 함수는 <stdlib.h>에 정의되어 있습니다. 헤더 파일.

<시간>

C malloc()

"malloc"이라는 이름은 메모리 할당을 나타냅니다.

malloc() 함수는 지정된 바이트 수의 메모리 블록을 예약합니다. 그리고 void의 포인터를 반환합니다. 모든 형식의 포인터로 캐스팅될 수 있습니다.

<시간>

malloc()의 구문

ptr = (castType*) malloc(size);

ptr = (float*) malloc(100 * sizeof(float));

위의 명령문은 400바이트의 메모리를 할당합니다. float의 크기 때문입니다. 4바이트입니다. 그리고 포인터 ptr 할당된 메모리의 첫 번째 바이트 주소를 보유합니다.

표현식 결과 NULL 메모리를 할당할 수 없는 경우 포인터입니다.

<시간>

C calloc()

"calloc"이라는 이름은 연속 할당을 나타냅니다.

malloc() 함수는 메모리를 할당하고 메모리를 초기화하지 않은 상태로 둡니다. 반면에 calloc() 함수는 메모리를 할당하고 모든 비트를 0으로 초기화합니다.

<시간>

calloc()의 구문

ptr = (castType*)calloc(n, size);

예:

ptr = (float*) calloc(25, sizeof(float));

위의 명령문은 float 유형의 요소 25개에 대해 메모리에 연속 공간을 할당합니다. .

<시간>

C 무료()

calloc()로 생성된 동적으로 할당된 메모리 또는 malloc() 저절로 풀리지 않습니다. free()을 명시적으로 사용해야 합니다. 공간을 해제합니다.

<시간>

free()의 구문

free(ptr);

이 문은 ptr이 가리키는 메모리에 할당된 공간을 해제합니다. .

<시간>

예제 1:malloc() 및 free()

// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n, i, *ptr, sum = 0;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) malloc(n * sizeof(int));
 
  // if memory cannot be allocated
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  
  // deallocating the memory
  free(ptr);

  return 0;
}

출력

Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156

여기에서 n에 대한 메모리를 동적으로 할당했습니다. int의 수 .

<시간>

예시 2:calloc() 및 free()

// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n, i, *ptr, sum = 0;
  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) calloc(n, sizeof(int));
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  free(ptr);
  return 0;
}

출력

Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
<시간>

C realloc()

동적으로 할당된 메모리가 부족하거나 필요 이상인 경우 realloc()을 사용하여 이전에 할당된 메모리의 크기를 변경할 수 있습니다. 기능.

<시간>

realloc()의 구문

ptr = realloc(ptr, x);

여기, ptr 새 크기 x로 재할당됩니다. .

<시간>

예시 3:realloc()

#include <stdio.h>
#include <stdlib.h>

int main() {
  int *ptr, i , n1, n2;
  printf("Enter size: ");
  scanf("%d", &n1);

  ptr = (int*) malloc(n1 * sizeof(int));

  printf("Addresses of previously allocated memory:\n");
  for(i = 0; i < n1; ++i)
    printf("%pc\n",ptr + i);

  printf("\nEnter the new size: ");
  scanf("%d", &n2);

  // rellocating the memory
  ptr = realloc(ptr, n2 * sizeof(int));

  printf("Addresses of newly allocated memory:\n");
  for(i = 0; i < n2; ++i)
    printf("%pc\n", ptr + i);
  
  free(ptr);

  return 0;
}

출력

Enter size: 2
Addresses of previously allocated memory:
26855472
26855476

Enter the new size: 4
Addresses of newly allocated memory:
26855472
26855476
26855480
26855484

C 언어

  1. 읽기 전용 메모리(ROM)
  2. 마이크로프로세서
  3. C++ 메모리 관리:신규 및 삭제
  4. Cervoz는 차세대 DDR4-2666 메모리 업그레이드
  5. 예제를 사용한 C++ 배열 동적 할당
  6. 프로그램 예제가 있는 C 라이브러리의 calloc() 함수
  7. C 라이브러리의 realloc() 함수:어떻게 사용합니까? 구문 및 예
  8. C - 메모리 관리
  9. 전통적인 소매업의 가격 변동은 불가피합니다
  10. C++ 동적 메모리