1. 程式人生 > >c++中*p=a和p=&a的區別

c++中*p=a和p=&a的區別

#include <iostream>

using namespace std;

int main()
{
    int a = 10;
    int *PA = new int;
    *PA = a;
    cout << "*PA is:" << *PA << endl;    //輸出10

    int *PB = NULL;
    PB = &a;
    //*PB = a;     //這樣子賦值會出現錯誤
    cout << "*PB is:" << *PB << endl;     //輸出10

    delete PA;     //記得用delete釋放指標佔用的記憶體

    PA=NULL;     //然後使指標指向空

    return 0;
}

二者區別:

*PA=a;     表示把a的值賦值給PA所指的堆記憶體地址,PA本身沒變。

PB=&a;    表示指標PB指向變數a的地址,PB本身變了。