18일 - 메모리 할당 malloc()
sizeof 단항 연산자와 포인터에 메모리를 할당하는 방법에 대해 알아보았습니다."malloc"이라는 이름은 메모리 할당을 나타냅니다.
malloc() 함수는 지정된 바이트 수의 메모리 블록을 예약합니다. 그리고 모든 형식의 포인터로 변환할 수 있는 void의 포인터를 반환합니다.malloc() 구문 -
ptr = (data-type*) malloc(size);
예시:
ptr = (float*) malloc(100 * sizeof(float));
위의 명령문은 400바이트의 메모리를 할당합니다.
float의 크기가 4바이트이기 때문입니다. 그리고 포인터ptr는 할당된 메모리의 첫 번째 바이트 주소를 보유합니다.메모리를 할당할 수 없는 경우 표현식 결과는
NULL 포인터입니다.배열 요소의 합계를 계산하는 예
#include <stdio.h>
#include <stdlib.h>
void  main() {
    int n,*arr,sum = 0;
    printf("Enter Number of Elements - ");
    scanf("%d",&n);
    arr = (int *)malloc(n * sizeof(int)); // Allocating Memory for n elements of the array.
    if(arr==NULL) {
        printf("Sorry! unable to Allocate Memory");
        exit(0);
    }
    for ( int i = 0; i < n ; i++) {
        scanf("%d",arr + i);
        sum += *(arr + i);
    }
    printf("\nSum of Elements = %d",sum);
    free(arr); // Release memory allocated.
}
Note - Because
mallocmight not be able to service the request, it might return a null pointer. It is important to check for this to prevent later attempts to dereference the null pointer.
Reference
이 문제에 관하여(18일 - 메모리 할당 malloc()), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/envoy_/day-18-memory-allocation-malloc-1ae2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)