new

new其实就是告诉计算机开辟一段新的空间,但是和一般的声明不同的是,new开辟的空间在堆上,而一般声明的变量存放在栈上。通常来说,当在局部函数中new出一段新的空间,该段空间在局部函数调用结束后仍然能够使用,可以用来向主函数传递参数。另外需要注意的是,new的使用格式,new出来的是一段空间的首地址。所以一般需要用指针来存放这段地址。

The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

利用new动态创建变量和数组

 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
/**************************************************************** 
 * Description:  C++  new 
 * Author: Alex Li
 * Date: 2024-03-25 22:38:04
 * LastEditTime: 2024-03-25 22:49:55
****************************************************************/
#include <iostream>
using  namespace std;

int main(){
    
    int n,a;
    a=3;
    int *p0,*p1;
    p0=new int;  //创建一个存储整型变量的空间,把地址给到p0
    p1=new int(2); //把变量初始化成2, int()这样是初始化为0
    p0=&a;
    cout<<*p0<<endl;
    cout<<*p1<<endl;
    
    cin>>n;
    int *p;
    p=new int[n]; //C++语言中创建动态数组
    for(int i=0;i<n;i++){
        //cin>>p[i];
         cin>>*(p+i);  
    }

    for (int i = 0; i <n; i++){
       // cout<<p1[i]<<' ';
        cout<<*(p+i)<<' ';
    }
    delete[] p; //C++语言中释放空间
    return 0;
}
Scroll to Top