C++ new
C++中利用new操作符在堆區開辟數據
堆區開辟的數據,由程序員手動開辟,手動釋放,釋放利用操作符 delete
?
語法:new 數據類型
利用new創建的數據,會返回該數據對應的類型的指針
開辟單個內存
語法:new 數據類型(初始值)
#include <iostream>
using namespace std;
int* get_num()
{int* a = new int(10);return a;
}
int main()
{int* res = get_num();cout<<*res<<endl;delete res;return 0;
}
開辟數組
#include <iostream>
using namespace std;
int main()
{// 開辟一維數組int* a = new int[10];for(int i = 0;i<10;i++)a[i] = i;for(int i = 0;i<10;i++)cout<<a[i];cout<<endl;// 開辟一維數組的同時賦值int* a2 = new int[5]{1,2,3};for(int i = 0;i<5;i++)cout<<a2[i];cout<<endl;// 開辟二維數組// int (*a3)[5]表示數組指針int (*a3)[5] = new int[5][5];for(int i = 0;i<5;i++){for(int j = 0;j<5;j++)a3[i][j] = 10;}cout<<*(a3[4]+4)<<endl;// 開辟二維數組的同時賦值// int (*a4)[5]表示數組指針int (*a4)[5] = new int[5][5]{{1,2,3,4,5},{6,7,8,9,10}};cout<<a4[1][2]<<endl;
}
delete
delete釋放的是開辟的內存中的變量,開辟的內存實際沒有被釋放。
#include <iostream>
using namespace std;
int main()
{int *a = new int(5);delete a;// a所指向的地址依舊存在,沒有被釋放cout<<a<<endl;// a所指向的地址中的值被釋放,此時*a是一個垃圾數cout<<*a<<endl;*a = 100;cout<<*a<<endl;
}
總結
- 上一篇: 左尺桡骨拍片多少钱
- 下一篇: C++二维数组名与数组指针的思考