>  기사  >  백엔드 개발  >  C 언어에서는 메모리를 동적으로 할당하기 위해 malloc 함수를 사용합니다.

C 언어에서는 메모리를 동적으로 할당하기 위해 malloc 함수를 사용합니다.

WBOY
WBOY앞으로
2023-09-18 11:41:141110검색

C 언어에서는 메모리를 동적으로 할당하기 위해 malloc 함수를 사용합니다.

malloc() 함수는 메모리 할당을 나타내며 동적으로 메모리를 할당합니다.

지정된 크기의 메모리 공간을 예약하고 메모리 위치에 대한 널 포인터를 반환합니다.

malloc() 함수는 가비지 값을 전달합니다. 반환된 포인터는 void 유형입니다.

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

ptr = (castType*) malloc(size);

Example

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

Live Demonstration

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
   char *MemoryAlloc;
   /* memory allocated dynamically */
   MemoryAlloc = malloc( 15 * sizeof(char) );
   if(MemoryAlloc== NULL ){
      printf("Couldn&#39;t able to allocate requested memory</p><p>");
   }else{
      strcpy( MemoryAlloc,"TutorialsPoint");
   }
   printf("Dynamically allocated memory content : %s</p><p>", MemoryAlloc);
   free(MemoryAlloc);
}

Output

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

Dynamically allocated memory content: TutorialsPoint

위 내용은 C 언어에서는 메모리를 동적으로 할당하기 위해 malloc 함수를 사용합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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