为什么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));
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP