如何使用new关键字在C ++中创建动态整数数组

在C ++中,可以使用new关键字创建动态数组,也可以使用delete关键字将其删除。

让我们考虑一个简单的例子。

范例程式码

#include<iostream>
using namespace std;
int main() {
   int i,n;
   cout<<"输入元素总数:"<<"\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;
}

输出结果

输入元素总数: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)来检索占用的内存。