Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

เหตุใด C ++ จึงต้องการการแคสต์สำหรับ malloc () แต่ C ไม่ต้องการ


ในภาษา C ตัวชี้เป็นโมฆะจะถูกแปลงโดยปริยายเป็นประเภทตัวชี้วัตถุ ฟังก์ชัน malloc() ส่งคืนค่า void * ในมาตรฐาน C89 ในเวอร์ชันก่อนหน้าของ C malloc() จะคืนค่า char * ในภาษา C++ โดยค่าเริ่มต้น malloc() จะคืนค่า int ดังนั้น ตัวชี้จะถูกแปลงเป็นตัวชี้วัตถุโดยใช้การแคสต์ที่ชัดเจน

ต่อไปนี้เป็นรูปแบบการจัดสรรหน่วยความจำในภาษาซี

pointer_name = malloc(size);

ที่นี่

ชื่อตัวชี้ − ชื่อใดๆ ที่กำหนดให้กับตัวชี้

ขนาด − ขนาดของหน่วยความจำที่จัดสรรเป็นไบต์

ต่อไปนี้เป็นตัวอย่าง malloc() ในภาษา C

ตัวอย่าง

#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()

ขนาด − ขนาดของหน่วยความจำที่จัดสรรเป็นไบต์

ต่อไปนี้เป็นตัวอย่างของ malloc() ในภาษา C++

ตัวอย่าง

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