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