C++用指針動態分配空間——數組、數字
1、使用new關鍵字來分配內存
C++中的指針的真正用處是可以動態使用空間(內存)。C語言可以使用malloc函數來實現動態分配,其原理也是指針,但是C++有更好的方式——new關鍵字。
下面來試試這種新技術,在運行階段為一個int值分配未命名的內存,並使用指針來訪問這個值
int *pn = new int
new int告訴程序,需要適合存儲int的內存,new運算符根據類型來確定需要多少字節的內存
分配內存通用格式如下:
typeName * pointer_name = new typeName;
需要在兩個地方制定數據類型:用來制定需要什么樣的內存和用來聲明合適的指針
下面的實例程序演示了如何將new用於兩種不同的類型。
//chapter4.17 use_new.cpp
#include <iostream>
using namespace std;
int main()
{
int nights = 1001;
int * pt = new int; //給pt指針一個新的int內存
*pt = 1001;
cout << "nights value = ";
cout << nights << ": location " << &nights << endl;
cout << "int ";
cout << "value = " << *pt << ": location = " << pt << endl;
double * pd = new double;
*pd = 10000001.0;
cout << "double ";
cout << "value = " << *pd << ": location = " << pd << endl;
cout << "location of pointer pd: " << &pd << endl;
cout << "size of pt = " << sizeof(pt);
cout << " : size of *pt = " << sizeof(*pt) << endl;
cout << "size of pd = " << sizeof(pd);
cout << " : size of *pd = " << sizeof(*pd) << endl;
return 0;
}
以下是程序的輸出:
nights value = 1001: location 0x71fe34
int value = 1001: location = 0x1d1590
double value = 1e+007: location = 0x1d15b0
location of pointer pd: 0x71fe28
size of pt = 8 : size of *pt = 4
size of pd = 8 : size of *pd = 8
- 使用delete釋放內存
C++可以用new來申請空間,但是內存空間會滿的,所以另一個關鍵字出現了——delete,用來釋放空間,用new申請過來的內存池被占用一部分,用完使用delete語句將其釋放,防止內存占滿,報廢……
實例:
int * ps = new int;
... //執行操作
delete ps;
此實例可以將ps指針直接釋放掉
亂使用delete是不安全的,下面列舉一個指針的用法,和是否安全
int * ps = new int; //ok
delete ps; //ok
delete ps; //不ok因為ps已經刪除
int jugs = 5;
int * pi = &jugs;
delete pi; //不行,不允許,內存沒分配
- 使用new創建動態數組
其實數組就是指針!
還是用new關鍵字,malloc同樣可以。
int * psome = new int [10]; //附10個下邊空間
刪除一個數組的時候也用delete,改成如下方法
delete [] psome;
通用分配格式:
type_name * pointer_name = new type_name [num_elements];
- 使用動態數組
如何使用呢?
先定義一個
int * psome = new int [10];
那么現在psome就是一個數組了
實例:
#include <iostream>
using namespace std;
int main()
{
double * p3 = new double[3]; //3個元素的數組
p3[0] = 0.2;
p3[1] = 0.5;
p3[2] = 0.8;
cout << "p3[1] is: " << p3[1] << ".\n";
p3 += 1;
cout << "now p3[0] is:" << p3[0] << endl;
p3 -= 1;
delete [] p3;
return 0;
}
其中p3+=1這一句是可以將整個數組的所有地址加一,所以錯位了p3[0]等於了原來的p3[1]
最后刪除的時候,p3必須恢復(p3-=1)原狀,才可以刪除,否則有一個元素空了,會報錯!
還可以用變量定義數組下標個數
例如
const int cc = 11;
int *p = new int[cc];
這樣子定義數組的時候可以用指針了,不一定非用向量了,可以最節省空間!力扣刷題找到了新方法