Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

0.2-Pointer #32

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Pointer觀念延續C


宣告

type * name;
type * name = address;
type * nameA,  * nameB;

int * p;

(有老師建議星號*左右兩邊都應該有空格)


取值 name 存取指標。 取得存放在指標中的的記憶體位址。 *name(取值運算子) 存取指標管理的記憶體。 取得指標所管理的記憶體空間中的值。

指派 name = address; 存取指標。 將 = 右側的記憶體位址指派給 = 左側的指標 ,指派後指標便可以透過這個記憶體位址,管理該記憶體空間。 *name = value; 存取指標管理的記憶體。 將 = 右側的值指派給 = 左側的指標所管理的記憶體空間。


address & 取得一個已存在的變數的記憶體位址。 new 配置指定型別的記憶體空間,並回傳該空間的記憶體位址。

new int 表示新增一個記憶體空間給int

另一個指標 將己存在的指標所儲存的記憶體位址,指派給另一個指標。

delete 指標 釋放指標所指的記憶體空間。 用 new 配置給指標的記憶體空間可以用delete釋放。 new 和 delete皆是C++專有語法, 類似C的 malloc和free

    int * p_a;
    p_a = new int;
    *p_a = 10;

    cout<<p_a<<endl;
    cout<<*p_a<<endl;

    delete p_a;

    cout<<p_a<<endl;
    cout<<*p_a<<endl;
0x556b70c0deb0
10
0x556b70c0deb0
0(因為被delete了, 所以可能會產生亂數或回復初始化等等, 為未定義行為)

const

宣告

type * const name; 記憶體內的值可以修改, 但是不可以修改記憶體位置->name 是 ROM const type * name; ROM, 記憶體內的值不能被修改, 但可以修改記憶體位置 ->name 是 ROM 其中`const type name;`最常被使用, 通常當成function的參數


type * const name; ->name 是 ROM

    int * const p = new int;
    *p = 200;
    delete p;
    //p = new int; 會編譯錯誤, p只能修改裡面的值, 但記憶體位置不能更動
error: assignment of read-only variable ‘p’

const type * name; ->*name 是 ROM

    const int * p = new int;
    //*p = 200;會編譯錯誤, p只能修改裡面的值, 但記憶體位置不能更動
    delete p;
    p = new int;
error: assignment of read-only location ‘* p’

const 和 function

const int function (const int p){...}

其中的(const int * p 代表告訴使用此function的人, *p也就是p的值不會被任意更動, 請放心使用此function

#include <iostream>

using namespace std;

const int * get_address(const int * p){
    int * q = new int;
    *q = *p;
    *q += 100;
    return q;
}

int main()
{
    int * m = new int;
    *m = 1;
    const int * n = get_address(m);
    //如果使用int * n = get_address(m); 編譯失敗
    //改變n的值也會編譯失敗 *n = 10, 因為function中的參數為const(const int * p);

    cout<<*n<<endl;

    return 0;
}

const type * function(arg){...} const宣告在function return type前面時, 代表return的記憶體位置的值是不可變動的,要接收的值也必須是const

 const int * n = get_address(m);

參考資料 https://cpproadadvanced.blogspot.com/2019/06/c-pointer.html