2012-02-09 61 views
3

在下列情況下,我得到NumRecPrinted = 0,即num爲0傳遞指針函數沒有返回值

int main() 
{ 
    int demo(int *NumRecPrinted); 
    int num = 0; 
    demo(&num); 
    cout << "NumRecPrinted=" << num; <<<< Prints 0 
    return 0; 
} 

int demo (int *NumRecPrinted) 

{ 
    int no_of_records = 11; 
    NumRecPrinted = &no_of_records; 
} 
+2

您沒有更改int的值,您已經爲指針指定了新的地址。這應該是'* NumRecPrinted = no_of_records;' – 2012-02-09 14:33:15

回答

6

您將地址分配給指針,而不是指向指向的值。嘗試像這樣反而

int demo (int *NumRecPrinted) 
{ 
    int no_of_records = 11; 
    *NumRecPrinted = no_of_records; 
} 
6

沒有!

*NumRecPrinted = no_of_records; 

查看 「*」 表示和 「&」 的意思是 「地址」, 「價值」。您想要更改NumRecPrinted的「值」,這就是上述原因。你所做的就是給NumRecPrinted「num_of_records的地址」。

2

,你卻指針本地指針到INT在demo函數內一個新的整數NumRecPrinted

你想改變它指向的整數,而不是改變它指向的地方。

*NumRecPrinted = no_of_records; 

可以看到您的版本,你正在做一個局部變量的地址,你知道這是不是你關心的是變量的地址,但它的價值。

0

你想 * NumRecPrinted = no_of_records;

這意味着,「設置的事情NumRecPrinted點等於no_of_records」。

1

正如其他人所指出的那樣,* =的價值和& =地址。所以你只是分配一個新的地址給方法內的指針。你應該:

*NumRecPrinted = no_of_records; 

看到這個優秀的教程Pointers。例如:

int firstvalue = 5, secondvalue = 15; 
    int * p1, * p2; 

    p1 = &firstvalue; // p1 = address of firstvalue 
    p2 = &secondvalue; // p2 = address of secondvalue 
    *p1 = 10;   // value pointed by p1 = 10 
    *p2 = *p1;   // value pointed by p2 = value pointed by p1 
    p1 = p2;   // p1 = p2 (value of pointer is copied) 
    *p1 = 20;   // value pointed by p1 = 20