指針
先看一個簡單的例子:
#include <iostream> using namespace std; int main() { // your code goes here int num = 123; int* p = # cout<<"p:"<<p<<endl; cout<<"*p:"<<*p<<endl; cout<<"num:"<<num<<endl; cout<<"&num:"<<&num<<endl; return 0; }
運行結果:
p:0x7ffc2861549c
*p:123
num:123
&num:0x7ffc2861549c
p是指向num地址的指針,所以p的值為num的地址。可以給*p賦值,此時num值也會發生相應的變化,但是不會因此而改變p所指向的地址。
#include <iostream> using namespace std; int main() { int num = 123; int* p = # // 這里&為取址 cout<<"*p = "<<*p<<endl; cout<<"p = "<<p<<endl; *p = NULL; cout<<"*p = "<<*p<<endl; cout<<"p = "<<p<<endl; cout<<"num = "<<num<<endl; }
*p = 123
p = 0x7ffccb7a153c
*p = 0
p = 0x7ffccb7a153c
num = 0
引用
類型標識符 &引用名=目標變量名
#include <iostream> using namespace std; int main() { int num1 = 1, num2 = 2; int &ref1 = num1, &ref2 = num2; ///引用必須要初始化 cout<<"num1 = "<<num1<<",num2 = "<<num2<<endl; cout<<"ref1 = "<<ref1<<",ref2 = "<<ref2<<endl; ///修改引用的值將改變其所綁定的變量的值 ref1 = -1; cout<<"num1 = "<<num1<<",ref1 = "<<ref1<<endl; ///將引用b賦值給引用a將改變引用a所綁定的變量的值, ///引用一但初始化(綁定),將始終綁定到同一個特定對象上,無法綁定到另一個對象上 ref1 = ref2; cout<<"num1 = "<<num1<<",ref1 = "<<ref1<<endl; return 0; }
num1 = 1,num2 = 2
ref1 = 1,ref2 = 2
num1 = -1,ref1 = -1
num1 = 2,ref1 = 2
指向指針的指針
#include <iostream> using namespace std; int main() { int val = 1; int *p1 = &val; int **p2 = &p1;///**聲明一個指向指針的指針 cout<<"val = "<<val<<endl; cout<<"p1 = "<<p1<<", *p1 = "<<*p1<<endl; cout<<"p2 = "<<p2<<", *p2 = "<<*p2<<",**p2 = "<<**p2<<endl; return 0; }
val = 1
p1 = 0x7ffe520c3d34, *p1 = 1
p2 = 0x7ffe520c3d38, *p2 = 0x7ffe520c3d34,**p2 = 1
指針與數組
#include <iostream> using namespace std; int main() { int arr[5][5]; arr[2][1] = 666; cout<<*(*(arr + 2) + 1)<<endl; return 0; }
#include <iostream> using namespace std; int main() { int arr[100]; for (int i = 0; i < 100; i++) arr[i] = i; int *p = arr; //等價於int *p = &arr[0]; //數組的變量名就是一個指針 cout<<"p = "<<p<<",*p = "<<*p<<endl; //p = 0x7ffe3b44b8b0,*p = 0 int t = 100; while (t--) ///可以直接對指針進行加減運算,就和迭代器一樣 cout<<*(p++)<<endl; //輸出0~99 ///指針可以做差: int *p2 = &arr[10], *p3 = &arr[20]; cout<<"p2 - p3 = "<<(p2 - p3)<<endl; //p2 - p3 = -10 ///還可以比比較大小: cout<<(p2 < p3 ? p3 - p2 : p2 - p3)<<endl; //10 return 0; }