C / C ++中的malloc()vs new()
malloc()
该函数malloc()用于分配请求的字节大小,并返回指向已分配内存的第一个字节的指针。如果失败,则返回空指针。
这是malloc()C++语言的语法,
pointer_name = (cast-type*) malloc(size);
这里,
pointer_name-给指针的任何名称。
cast-type-您要通过强制转换分配的内存的数据类型malloc()。
大小-以字节为单位分配的内存大小。
这是malloc()C语言的示例,
示例
#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
在上面的程序中,声明了四个变量,其中之一是指针变量*p,它存储由malloc分配的内存。我们正在打印元素的总和。
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);新()
新运算符请求在堆中分配内存。如果有足够的内存可用,它将初始化该内存为指针变量并返回其地址。
这是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;