2014-01-12 43 views
0

我有一個集合的值,我想分配一個指針指向集合中的一個項目。如何更改指針指向不同的對象?

下面是一個類似的例子不工作:

void changeVar(int * var) { 
     int newInteger = 99; 
     var = &newInteger; 
} 

int main() { 
    // create a random pointer and initialize to NULL 
    int * randomPointer= 0; 

    // the printf prints out it's address as 0. good. 
    printf("address: %d \n\r", randomPointer); 

    // pass the pointer to a function which should change where the pointer points 
    changeVar(randomPointer); 

    // the printf below should print the value of the newInteger and randomPointer should point to newInteger value address 
    printf("value: %d \n\r", *randomPointer); 

return 0; 
} 

我如何使changeVar功能後,randomPointer點newInteger的地址?

PS。 randomPointer必須是指針

回答

1

您需要將引用(指向指針的指針)傳遞給您的函數。這樣你可以告訴函數「改變這個位置的值」。

void changeVar(int **pp){ 
    static int n=99; 
    *p = &n; 
} 

注 - 您需要static,因爲一旦您離開該功能,內存位置將會無效。現在你叫它

changeValue(&randomPointer); 
2

要進行更改,以var傳播回調用方,則需要通過指針傳遞var

void changeVar(int** var) { 
     (*var) = ...; 
} 

這就是說,newInteger超出範圍的那一刻changeVar回報,所以之後你不應該保留指針。取消引用這樣的指針會導致undefined behaviour

+0

是的。我舉了一個壞榜樣。在真實情況下,對象是靜態的 –

相關問題