[C/C++] C語言的指標(pointer)與參照(reference)

[C/C++] C語言的指標(pointer)與參照(reference) - tilt

自己作為一個初學者。覺得C/C++的精隨應該就是在指標了,為了幫助自己釐清觀念,特別整理這篇文章方便自己回顧,如果對大家有幫助的話,可以加入我的最愛,常常來看喔!當然留言是最好的,因為小獅我啊~最喜歡跟人類互動了!

1. 首先,我們先建立一個字串

string a = "There is no spoon.";

印出它的位置和內容看看:

cout << "a:t" << a << endl;    // a:      There is no spoon.
cout << "&a:t" << &a << endl;  // &a:     0x28fef4

根據結果,我們可以畫出以下的示意圖:

[C/C++] C語言的指標(pointer)與參照(reference) - 01

2. 再來,我們建立一個指標指向a

string *b = &a;

一樣,印出它的位置和內容看看:

cout << "b:t" << b << endl;    //b:      0x28fef4
cout << "&b:t" << &b << endl;  //&b:     0x28fef0

示意圖:

[C/C++] C語言的指標(pointer)與參照(reference) - 02

又因為它的內容與a的地址相符,我們稱它為”a的指標”

[C/C++] C語言的指標(pointer)與參照(reference) - 03

3. 再來,我們建立一個參照c

string &c = a;

一樣,印出它的位置和內容看看:

cout << "c:t" << c << endl;    //c:      There is no spoon.
cout << "&c:t" << &c << endl;  //&c:     0x28fef4

根據結果,我們可以畫出以下的示意圖:

[C/C++] C語言的指標(pointer)與參照(reference) - 04

咦~好像有點似曾相識;沒錯,除了名子之外,全部都與”a字串”如出一轍!

也就是說,它其實應該像這樣:

[C/C++] C語言的指標(pointer)與參照(reference) - 05

也就是說,我們可以直接把參照理解成別名的概念

4. 最後,我們再建立一個指標d,並指向匿名字串

string *d = new string("There is no spoon.");

印出它的位置和內容看看:

cout << "d:t" << d << endl;    //d:      0x7c10f0
cout << "&d:t" << &d << endl;  //&d:     0x28feec

示意圖:

[C/C++] C語言的指標(pointer)與參照(reference) - 06

酷吧!雖然它指向的是一個匿名的字串物件,但是它依舊是一個指標,其特性絲毫沒有受到影響喔!

 

 

 

完整範例程式碼:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string a = "There is no spoon.";
    cout << "a:t" << a << endl;
    cout << "&a:t" << &a << endl;

    //b為對 a 的指標
    string *b = &a;
    cout << "b:t" << b << endl;
    cout << "&b:t" << &b << endl;

    //c為對 a 的參考
    string &c = a;
    cout << "c:t" << c << endl;
    cout << "&c:t" << &c << endl;

    //d為另一個指標
    string *d = new string("There is no spoon.");
    cout << "d:t" << d << endl;
    cout << "&d:t" << &d << endl;

    return 0;
}

/* 
    修改自:
        《程式語言教學誌》的範例程式
        http://pydoing.blogspot.com/
        檔名:pointerdemo2.cpp
        功能:示範 C++ 程式
        作者:張凱慶
        時間:西元 2012 年 10 月
*/

結果:

a:      There is no spoon.
&a:     0x28fef4
b:      0x28fef4
&b:     0x28fef0
c:      There is no spoon.
&c:     0x28fef4
d:      0x7c10f0
&d:     0x28feec

Process returned 0 (0x0)   execution time : 0.100 s
Press any key to continue.

 

One response to “[C/C++] C語言的指標(pointer)與參照(reference)

  1. 您好,請問一下你的示意圖好像不見了,點開來都無法顯示,麻煩您了,謝謝。

Brian 發表迴響取消回覆