第四章 指標 Pointer(入門),第四章pointer
第三章
指標 Pointer
我第一次上網求助,就是在pointer方面遇到了問題,對於我本人來說,有些時候reference和de-reference,address、location、value經常會弄混的,就連我的教授都自己坦言,不僅C++的初學者都會在pointer方面遇到這樣那樣的問題,而且一些從業多年的編程大神也會遇到指標上面的問題。
有一個笑話,當你學會了指標才能懂:
一個編程的人剛剛完成了一個項目的編程,但是有一個bug總是出現,在他苦苦思索之時,平時打掃衛生的保潔阿姨在旁邊說:“小夥子啊,泄漏了”。
在這裡我們引入三個新的概念:
A new kind of type: reference (also called “address”).
An operator (&) to acquire the address of a variable
An operator (*) to use the address of a variable
舉個例子in pseudocode
Integer myNum ← 7
print "the value stored in myNum is ", myNum
print "the address of myNum is ", &myNum
這時候,第二行數字將會顯示一串數字,那麼這段數字就是address
Integer myNum // This declares an integer
refToInteger myNumPtr // This declares a pointer to an integer
當我們每當用到一個variable前,首先要declare這個variable的type和名稱
Integer myNum
refToInteger myNumPtr
myNum ← 7
myNumPtr ← &myNum // This puts the address of myN
//into the variable myNumPtr
在這種情況,myNum will contain 7,while the the variable
myNumPtr will contain 4683953 (or whatever address is given to the variable)。在這時,address不一定會是這個數字。
當在賦值之前,這個pointer是garbage
A valid pointer contains the address of some data.
The pointer "points to" the data.
Following the pointer is called "de-referencing" the pointer.
Problem: dereferencing has 2 related but distinct meanings.
To refer to the value stored at the address (for use in normal
calculations)
To allow storage of data at the address (for use in assignment
Statements)
那麼現在我們想從一個pointer這裡得到一個數字
Integer myNum ← 7
refToInteger myNumPtr ← &myNum
print "the value stored in myNum is", myNum
print "the value, again, is", *myNumPtr
myNum ← *myNumPtr + 1 // Pay attention to this line
*myNumPtr的意思就是dereference,就是從一個pointer的address中讀出其中的實際含義。
在上面的例子中,我們已知:
refToInteger myNumPtr 是一個指向integer的指標
myNumptr是一個address
*myNumPtr是一個value,which contain in address,就是7
7+1等於8
然後*myNumPtr的值不變,給myNum重新賦值。
另一個例子:
Integer myNum ← 7
refToInteger myNumPtr ← &myNum
*myNumPtr ← *myNumPtr + 1 // Pay attention to this line
在這裡:
myNum 是一個integer,值為7
myNumptr是一個 pointer to a integer,//他的值會是一段地址的代碼,並沒有實際含義//,並且將myNum的地址複製給myNumPtr。
所以這時候,*myNumPtr的值為7
然後是*myNumPtr 的自加,所以這時候*myNumPtr 將會是8
然而,myNum的值還是7
記住一點,A operation B時,A和B總會是一樣的type(除非有強制轉換格式)所以說,在一般的判斷的時候,首先先檢查一下“=”和“==”左右兩邊是否為同樣的格式。
假如說
1:
myNumPtr=1;
這時候,我們知道myNumPtr是一個pointer,他的值是一個address 多半是一串數字,而賦值符號右邊是一個integer 1, 所以這是錯誤的。
2:
*myNumptr=&myNum
這時候,賦值等號左邊是一個值,一個指標所指的一個value,而右邊是一個address,所以這也是錯誤的
3:
Int a=‘a’;
這時候,賦值左邊是一個integer a, 我們要給a賦值,所以只能是一個integer,而賦值等號的右邊,是一個char格式的值,所以這是錯誤的。
綜上所述,在我們遇到一些相如是指標這類的問題的時候,記住,一定要注意左右邊是否是同樣的格式。