使用指针时会频繁进行以下几个操作:定义一个指针变量、把变量地址赋值给指针、访问指针变量中可用地址的值。这些是通过使用一元运算符 * 来返回位于操作数所指定地址的变量的值。下面的实例涉及到了这些操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <iostream> using namespace std; int main () { int var = 20; int *ip, *iq; ip = &var; cout << "Value of var variable: "; cout << var << endl; cout << "Address stored in ip variable: "; cout << ip << endl; cout << "Value of *ip variable: "; cout << *ip << endl; var++; cout << "var++, then Value of *ip variable: "; cout << *ip << endl; *ip=*ip-10; cout<<"*ip-10 equal var-10: "; cout<<var<<' '<<*ip<<endl; iq=ip; cout<<"iq have the same the Address of ip, so *iq have the same Value of var "; cout<<*iq; return 0; } |
输出char类型的时候需要强转成void *
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main () { char *pc; char a='c'; pc=&a; string b="hello"; string *ps=&b; cout << "ptr value is " <<(void *)pc<<endl ; cout<<*pc<<endl; cout<<ps<<endl; cout<<&b; return 0; } |