2012-07-16 105 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; 
相关问题