如何使用 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