為什麼C++需要為malloc()進行型別轉換,而C不需要?


在C語言中,空指標會隱式轉換為物件指標型別。在C89標準中,malloc()函式返回void *。在早期版本的C語言中,malloc()返回char *。在C++語言中,malloc()預設返回int值。因此,需要使用顯式型別轉換將指標轉換為物件指標。

以下是C語言中分配記憶體的語法。

pointer_name = malloc(size);

這裡:

指標名 − 指標的名稱。

大小 − 以位元組為單位分配的記憶體大小。

以下是在C語言中使用malloc()的示例。

示例

 線上演示

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = 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 : 2 28 12 32
Sum : 74

在上面的C語言示例中,如果我們進行顯式型別轉換,將不會顯示任何錯誤。

以下是C++語言中分配記憶體的語法。

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

這裡:

指標名 − 指標的名稱。

轉換型別 − 你想將malloc()分配的記憶體轉換成的 資料型別。

大小 − 以位元組為單位分配的記憶體大小。

以下是C++語言中使用malloc()的示例。

示例

#include <iostream>
using namespace std;
int main() {
   int n = 4, i, *p, s = 0;
   p = (int *)malloc(n * sizeof(int));
   if(p == NULL) {
      cout << "\nError! memory not allocated.";
      exit(0);
   }
   cout << "\nEnter elements of array : ";
   for(i = 0; i < n; ++i) {
      cin >> (p + i);
      s += *(p + i);
   }
   cout << "\nSum : ", s;
   return 0;
}

輸出

Enter elements of array : 28 65 3 8
Sum : 104

在上面的C++語言示例中,如果不進行顯式型別轉換,程式將顯示以下錯誤。

error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
p = malloc(n * sizeof(int));

更新於:2020年6月26日

768 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告