,數值是有類型的,因此在聲明指針的時候要指明它所指向的。
;
int * number;
char * character;
double * decimals;
,不要把它和前面我們用過的引用操作符混淆,雖然那也是寫成一個星號 (*)。它們只是用同一符號表示的兩個不同任務。
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
//second example
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; //p1存儲的是firstvalue地址
p2 = &secondvalue; //p2存儲的是secondvalue地址
*p1 = 10; //指針p1指向的值為10,
//地址是firstvalue的地址,即firstvalue=10
*p2 = *p1; //secondvalue=10
p1 = p2; //p2存儲的地址給p1,p1指向secondvalue
*p1 = 20; //secondvalue= 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
注釋寫的很清楚了,自己要多練去理解。