Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 언어에서 Calloc이란 무엇입니까?

<시간/>

C 라이브러리 메모리 할당 함수 void *calloc(size_t nitems, size_t size)는 요청된 메모리를 할당하고 이에 대한 포인터를 반환합니다.

malloc과 calloc의 차이점은 malloc은 메모리를 0으로 설정하지 않는 반면 calloc은 할당된 메모리를 0으로 설정한다는 것입니다.

메모리 할당 기능

메모리는 아래에 설명된 대로 두 가지 방법으로 할당할 수 있습니다. -

C 언어에서 Calloc이란 무엇입니까?

컴파일 타임에 메모리가 할당되면 실행 중에는 변경할 수 없습니다. 메모리가 부족하거나 낭비되는 문제가 있습니다.

솔루션은 프로그램 실행 중 사용자의 요구 사항에 따라 동적으로 메모리를 생성하는 것입니다.

동적 메모리 관리에 사용되는 표준 라이브러리 함수는 다음과 같습니다. -

  • malloc( )
  • 호출()
  • 실제 할당( )
  • 무료( )

Calloc( ) 함수

  • 이 함수는 런타임에 연속적인 메모리 블록을 할당하는 데 사용됩니다.

  • 이것은 특별히 어레이용으로 설계되었습니다.

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

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

void *calloc ( numbers of elements, size in bytes)

예시

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

int *ptr;
ptr = (int * ) calloc (500,2);

여기에서 각각 크기가 2바이트인 500개의 메모리 블록이 연속적으로 할당됩니다. 할당된 총 메모리 =1000바이트.

C 언어에서 Calloc이란 무엇입니까?

int *ptr;
ptr = (int * ) calloc (n, sizeof (int));

예시 프로그램

다음은 동적 메모리 할당 함수 Calloc을 사용하여 요소 집합에서 짝수와 홀수의 합을 계산하는 C 프로그램입니다.

#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables, pointers//
   int i,n;
   int *p;
   int even=0,odd=0;
   //Declaring base address p using Calloc//
   p = (int * ) calloc (n, sizeof (int));
   //Reading number of elements//
   printf("Enter the number of elements : ");
   scanf("%d",&n);
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Storing elements into location using for loop//
   printf("The elements are : \n");
   for(i=0;i<n;i++){
      scanf("%d",p+i);
   }
   for(i=0;i<n;i++){
      if(*(p+i)%2==0){
         even=even+*(p+i);
      } else {
         odd=odd+*(p+i);
      }
   }
   printf("The sum of even numbers is : %d\n",even);
   printf("The sum of odd numbers is : %d\n",odd);
}

출력

위의 프로그램을 실행하면 다음과 같은 결과가 나온다 -

Enter the number of elements : 4
The elements are :
12
56
23
10
The sum of even numbers is : 78
The sum of odd numbers is : 23