8.2 使用指针(指针必须初始化)

Posted: March 25, 2011 in C++

/*对于指针,一定要初始化,如果不知道赋什么值给指针,可以将0赋给它.
值为0的指针被称为空指针.没有被初始化的指针被称为失控指针(wild pointer).
可能指向任何东西的指针是非常危险的,应该避免出现.

指针提供了一种间接方式来获取储存在地址处的值.

比如:
int number = 50;
int *pointer = &number;

cout<<*pointer;

*pointer门牌号记住了number的内存地址,用的时候直接”call门牌号”,就可以找到”这家人了”.
*/

#include <iostream>

using namespace std;

void main()
{
            int number=50;
            int *pointer=&number;//初始化pointer门牌号到number的地址

            cout<<*pointer<<endl;//打印pointer门牌号就是就是叫number

            number=60;//定义新number
            cout<<*pointer<<endl;//相应的门牌号不变,即地址不变,但是”人”变了

            *pointer=70;//通过门牌号,再换新”人”
            cout<<number<<endl;//把又换的新”人”叫出来

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s