2017-09-10 73 views
-4

我碰到這個問題,它創建了3塊內存,我很迷惑如果刪除* r,** r仍然存在與否?我應該將**移到* r的位置嗎? 我是否需要另一個「新的int」語句來賦值?刪除它後C++指針然後給出值

int t = 5; 
int **r; 
r = new int *; //declare pointer 
*r = new int; 
delete *r;  // delete pointer 
*r = t;   //give new value 

抱歉問錯了。仍然在學習。謝謝。

+0

如果你讀的問題,它走是一個整數。所以我編輯它讓它更有意義 –

+0

_「請不要在沒有閱讀的情況下投票。」反對票是絕對應得的。在提問時顯示[MCVE]!在你編輯你的問題之前,沒有證據表明't'是一個'int'。 – user0042

+0

對不起,我的壞,修復它 –

回答

1

你的代碼是正確的(Ideone):

#include <iostream> 
using namespace std; 

int main() { 
    int **r = new int *; // declare pointer to int* 
    cout << r << endl; // outputs some address in memory (pointer to int*) 
    cout << *r << endl; // outputs some garbage value 
// cout << **r << endl; // it's invalid 

    *r = new int;  // assign to memory pointed by r new value 
    cout << *r << endl; // outputs some address in memory (pointer to int) 
    cout << **r << endl; // outputs some garbage value 

    delete *r;   // delete pointer to int 
    cout << *r << endl; // outputs same address in memory, but we can't dereference it 
// cout << **r << endl; // it's invalid, because we deleted *r 

    // here you can acces r, *r, but not 
    return 0; 
} 
+0

我的教授給出了「** r = new int *」,我想應該是「r = new int *」 –

+0

@TaihongWang,你可以先定義變量'r'('int ** r;'),然後賦值('r = new int *;')或者你可以在一行中定義和賦值('int ** r = new int *') – diraria

+1

非常感謝,我修復了代碼。 –