C++ 关键字 - new 的用法
https://www.runoob.com/cprogramming/c-standard-library.html
位于C++ 标准库 #include
描述
new其实就是告诉计算机开辟一段新的空间,但是和一般的声明不同的是,new开辟的空间在堆上
,而一般声明的变量存放在栈上
。通常来说,当在局部函数中new出一段新的空间,该段空间在局部函数调用结束后仍然能够使用,可以用来向主函数传递参数。
另外需要注意的是,new的使用格式,new出来的是一段空间的首地址。所以一般需要用指针来存放这段地址。
一般用 delete
回收这个存储空间。
语法规则
1 2 3 4 5 6 7
| int *x = new int;
int *a = new int(100);
char *b = new char[10];
float *p=new float (3.14159);
|
用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include <iostream> using namespace std; int example1() { int *p = new int(3); int q = *new int; q = 1; cout << q << endl; return *p; }
int* example2() { int *q = new int[3]; for(int i=0; i<3; i++) q[i] = i; return q; } struct student { string name; int score; }; student* example3() { student *stlist = new student[3]{{"abc", 90}, {"bac", 78}, {"ccd", 93}}; return stlist; } int main() { int e1 = example1(); cout <<"e1: "<< e1 << endl; int *e2 = example2(); for(int i=0; i<3; i++) cout << e2[i] << " "; cout << endl; student *st1 = example3(); for(int i=0; i<3; i++) cout << st1[i].name << " " << st1[i].score << endl; return 0; }
|
返回值
该函数返回一个存储空间的首地址(指针)。一般用 delete
回收这个存储空间。