C/C++ 中的 malloc() 與 new()


malloc()

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

以下是 C++ 語言中 malloc() 的語法:

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

在上面的程式中,聲明瞭四個變數,其中一個是儲存 malloc 分配的記憶體的指標變數 *p。我們正在列印元素的總和。

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);

new()

new 運算子請求堆記憶體分配。如果可用足夠的記憶體,它會將記憶體初始化到指標變數並返回其地址。

以下是 C++ 語言中 new 運算子的語法:

pointer_variable = new datatype;

以下是初始化記憶體的語法:

pointer_variable = new datatype(value);

以下是分配記憶體塊的語法:

pointer_variable = new datatype[size];

以下是 C++ 語言中 new 運算子的示例:

示例

 線上演示

#include <iostream>
using namespace std;
int main () {
   int *ptr1 = NULL;
   ptr1 = new int;
   float *ptr2 = new float(223.324);
   int *ptr3 = new int[28];
   *ptr1 = 28;
   cout << "Value of pointer variable 1 : " << *ptr1 << endl;
   cout << "Value of pointer variable 2 : " << *ptr2 << endl;
   if (!ptr3)
   cout << "Allocation of memory failed\n";
   else {
      for (int i = 10; i < 15; i++)
      ptr3[i] = i+1;

      cout << "Value to store in block of memory: ";
      for (int i = 10; i < 15; i++)
      cout << ptr3[i] << " ";
   }
   return 0;
}

輸出

Value of pointer variable 1 : 28
Value of pointer variable 2 : 223.324
Value to store in block of memory: 11 12 13 14 15

在上面的程式中,聲明瞭三個指標變數 ptr1、ptr2 和 ptr3。指標變數 ptr1 和 ptr2 使用 new() 初始化值,ptr3 儲存 new() 函式分配的記憶體塊。

ptr1 = new int;
float *ptr2 = new float(223.324);
int *ptr3 = new int[28];
*ptr1 = 28;

更新於:2020年6月26日

5K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告