C語言中的malloc是什麼?


C 庫記憶體分配函式 void *malloc(size_t size) 分配請求的記憶體並返回指向它的指標。

記憶體分配函式

記憶體可以按照下面解釋的兩種方式分配:

一旦在編譯時分配了記憶體,就不能在執行期間更改它。將存在記憶體不足或記憶體浪費的問題。

解決方法是在程式執行期間根據使用者的需求動態建立記憶體。

用於動態記憶體管理的標準庫函式如下:

  • malloc ( )
  • calloc ( )
  • realloc ( )
  • free ( )

Malloc() 函式

此函式用於在執行時以位元組為單位分配記憶體塊。它返回一個 void 指標,該指標指向已分配記憶體的基地址。

malloc() 的語法如下:

void *malloc (size in bytes)

示例 1

以下示例顯示了 malloc() 函式的使用。

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

注意 - 如果記憶體不為空閒,則返回 NULL。

示例程式

以下是演示動態記憶體分配函式 - malloc() 的 C 程式。

 線上演示

#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointer//
   int numofele,i;
   int *p;
   //Reading elements as I/p//
   printf("Enter the number of elements in the array: ");
   scanf("%d",&numofele);
   //Declaring malloc function//
   p = (int *)malloc(numofele * (sizeof(int)));
   //Reading elements into array of pointers//
   for(i=0;i<numofele;i++){
      p[i]=i+1;
      printf("Element %d of array is : %d
",i,p[i]);    } }

輸出

執行上述程式時,會產生以下結果:

Enter the number of elements in the array: 4
Element 0 of array is : 1
Element 1 of array is : 2
Element 2 of array is : 3
Element 3 of array is : 4

示例 2

以下是使用動態記憶體分配函式顯示元素的 C 程式:

前五個塊應為空,後五個塊應包含邏輯。

 線上演示

#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 : 
");    for(i=0;i<numofe;i++){       scanf("%d",p+i);       sum=sum+*(p+i);    }    printf("
The sum of elements is %d",sum);    free(p);//Erase first 2 memory locations//    printf("
Displaying the cleared out memory location :
");    for(i=0;i<numofe;i++){       printf("%d
",p[i]);//Garbage values will be displayed//    } }

輸出

執行上述程式時,會產生以下結果:

Enter the number of elements : 5
Enter the elements :
12
10
24
45
67
The sum of elements is 158
Displaying the cleared out memory location :
7804032
0
7799120
0
67

更新於: 2021年3月17日

5K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告