如何在 C/C++ 中使用 malloc() 和 free()?


malloc()

該函式 malloc() 用於分配所需大小的位元組並返回一個指向已分配記憶體第一個位元組的指標。如果它失敗,則返回空指標。

以下是 malloc() 在 C 語言中的語法,

pointer_name = (cast-type*) malloc(size);

其中,

  • pointer_name  − 賦予該指標的任意名稱。

  • cast-type  − 希望 malloc() 將已分配記憶體強制轉換為的型別。

  • size  − 已分配記憶體的大小(以位元組為單位)。

以下是在 C 語言中 malloc() 的一個示例,

示例

 即時演示

#include <stdio.h>
#include <stdlib.h>

int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");

   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}

輸出

以下是輸出

Enter elements of array : 32 23 21 8
Sum : 84

free()

該函式 free() 用於釋放由 malloc() 分配的記憶體。它不會更改該指標的值,這意味著它仍然指向同一記憶體位置。

以下是 free() 在 C 語言中的語法,

void free(void *pointer_name);

其中,

  • pointer_name − 賦予該指標的任意名稱。

以下是在 C 語言中 free() 的一個示例,

示例

 即時演示

#include <stdio.h>
#include <stdlib.h>

int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));

   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");

   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   free(p);
   return 0;
}

輸出

以下是輸出

Enter elements of array : 32 23 21 28
Sum : 104

更新日期:2020 年 6 月 25 日

2K+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告