2012-07-16 147 views

回答

7

不。第一個更改指針(它現在指向a)。第二個改變指針指向的東西。

考慮:

int a = 5; 
int b = 6; 

int *ptr = &b; 

if (first_version) { 
    ptr = &a; 
    // The value of a and b haven't changed. 
    // ptr now points at a instead of b 
} 
else { 
    *ptr = a; 
    // The value of b is now 5 
    // ptr still points at b 
} 
0

不,ptr = &a您存儲變量的地址 'A' 變量 'PTR' 即像ptr=0xef1f23

in *ptr = a您正在將變量'a'的值存儲在指針變量'* ptr' 中,即類似*ptr=5之類的東西。

+0

感謝解釋這是怎麼回事引擎蓋下 – mko 2012-07-16 12:11:09

0

那麼,沒有。但要說明的類似行爲,添加到奧利查爾斯沃思的回答是:

考慮:

int a = 5; 
int* ptr = new int; 

if(first_version) { 
    ptr = &a; 
    //ptr points to 5 (using a accesses the same memory location) 
} else { 
    *ptr = a; 
    //ptr points to 5 at a different memory location 
    //if you change a now, *ptr does not change 
} 

編輯:對不起,使用new(C++不是C),但指針的事情不會改變。

0

兩者都不相同。

如果你修改a = 10的值,然後再次打印* ptr。這將只打印5.不10.

*ptr = a; //Just copies the value of a to the location where ptr is pointing. 
ptr = &a; //Making the ptr to point the a 
+2

嘗試學習[降價](HTTP:// daringfirebal l.net/projects/markdown/)用於解析stackoverflow問題/答案。它有很多幫助。你也可以點擊編輯別人的答案,看看他們是如何做到的。 – Shahbaz 2012-07-16 12:25:19

+0

當然。我會改進並感謝您的評論@Shahbaz。 – Jeyaram 2012-07-16 12:27:18

0

*ptr=&a C++編譯器將genrate錯誤becoz烏爾要ADDRES分配到ADRES ptr=&a,這是真的在這裏工作的PTR像變量,&一個是的一個ADDRES其中包含一些值

檢查,並嘗試

int *ptr,a=10; 
ptr=&a;output=10; 
相關問題