如何使用 new 关键字在 C++ 中创建一个整数动态数组
在 C++ 中,可以使用 new 关键字创建动态数组,可以使用 delete 关键字将其删除。
我们来看一个简单的例子。
示例代码
#include<iostream>
using namespace std;
int main() {
int i,n;
cout<<"Enter total number of elements:"<<"\n";
cin>>n;
int *a = new int(n);
cout<<"Enter "<<n<<" elements"<<endl;
for(i = 0;i<n;i++) {
cin>>a[i];
}
cout<<"Entered elements are: ";
for(i = 0;i<n;i++) {
cout<<a[i]<<" ";
}
cout<<endl;
delete (a);
return 0;
}输出
Enter total number of elements:7 Enter 7 elements 1 2 3 4 5 6 7 Entered elements are: 1 2 3 4 5 6 7
在此程序中,使用 new 关键字通过声明 int *a=new int(n) 来分配内存。可以通过调用 delete(a) 检索占用的内存。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP