/*
- 指针是一个变量,与所有变量一样,指针也占用内存空间
- 指针的特殊之处在于,指针包含的值(这里为0x558)被解读为内存地址,因此指针是一种指向内存单元的特殊变量
- 引用运算符(&)也叫地址运算符
*/#include<iostream>usingnamespace std;intmain(){int age =30;constdouble pi =3.1416;// use & to get the address of a variable// 作为一种约定,显示十六进制数时,应加上文本0x
cout <<"Integer age is at: 0x"<<&age << endl;
cout <<"Double pi is located at: 0x"<< hex <<&pi << endl;return0;}
2. 声明并初始化指针
#include<iostream>usingnamespace std;intmain(){int age =40;int* pointer =&age;// pointer to an int, initialized to &age// displaying the value of pointer
cout <<"Integer age is at: 0x"<< hex << pointer << endl;return0;}
3.引用运算符
/*这个程序表明,同一个int指针(pInteger)可指向任何int变量*/#include<iostream>usingnamespace std;intmain(){int age =30;int* pointer =&age;//pointer stores the address of age
cout <<"pointer points to age now"<< endl;// displaying the value of pointer
cout <<"pointer = 0x"<< hex << pointer << endl;int dogs_age =9;
pointer =&dogs_age;//pointer now points to dogs_age
cout <<"pointer now points to dogs_age"<< endl;
cout <<"pointer = 0x"<< hex << pointer << endl;return0;}
4. 解除引用运算符
/*解除引用运算符(*)也叫间接运算符*/#include<iostream>usingnamespace std;intmain(){int age =18;int dogs_age =3;int* pointer =&age;
cout <<"pointer points to age"<< endl;
cout <<"*pointer = "<<*pointer << endl;
pointer =&dogs_age;
cout <<"pointer points to dogs_age now"<< endl;
cout <<"*pointer = "<<*pointer << endl;int* pointer_1 =&dogs_age;
cout <<"Enter an age for your dog: ";
cin >>*pointer_1;
cout <<"Your dog is "<<*pointer_1 <<" years old."<< endl;return0;}