Friday, July 23, 2010

指標pointer

#include

using std::cin;
using std::cout;
using std::endl;

int main()
{
float x = 1.0;
float &y = x;
float* p; // p is a pointer. &x is address of x

cout << "original x is " << x <
p=&x;
cout << "after p=&x" < cout << " p = 0x"<< p << endl;
cout << "*p = "<< *p << endl;


y=7.3;

cout <<"after y=7.3"< cout << "x is "<< x <
cout << " p = 0x"<< p << endl;
cout << "*p = "<< *p << endl;


}



會顯示
original x is 1
after p=&x
p = 0x0012FF70
*p = 1
after y=7.3
x is 7.3
p = 0x0012FF70
*p = 7.3

可以看到雖然值被改變了,但是位置不會變

P是指標 指到x的位置
*p 是x的值

Labels