Computer >> Máy Tính >  >> Lập trình >> lập trình C

Giải thích hàm malloc trong lập trình C

Vấn đề

Viết chương trình C để hiển thị và thêm các phần tử bằng các hàm cấp phát bộ nhớ động.

Giải pháp

Trong C, hàm thư viện malloc cấp phát một khối bộ nhớ theo byte trong thời gian chạy. Nó trả về một con trỏ void, trỏ đến địa chỉ cơ sở của bộ nhớ được cấp phát và nó khiến bộ nhớ chưa được khởi tạo.

Cú pháp

void *malloc (size in bytes)

Ví dụ,

  • int * ptr;

    ptr =(int *) malloc (1000);

  • int * ptr;

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

Lưu ý - Nó trả về NULL, nếu bộ nhớ không còn trống.

Ví dụ

#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*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);
   }
   //Printing elements//
   printf("Enter the elements : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}

Đầu ra

Enter the number of elements : 5
Enter the elements :
23
45
65
12
23

The sum of elements is 168
Displaying the cleared out memory location :
10753152
0
10748240
0
23