2013-01-08 410 views
44

我在互聯網上閱讀了不同的東西,並且感到困惑,因爲每個網站都說不同的東西。「引用」和「解引用」的含義

談到C.

我讀到*引用運營商和&對其操作;或者引用意味着將指針指向一個變量,而解引用是訪問該指針指向的變量的值。所以我感到困惑。

我可以得到一個關於「引用和取消引用」的簡單但徹底的解釋嗎?

+2

http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=ptrs –

+6

請注意,官方名稱是地址('&')和間接('*')運算符。 –

+3

你讓運營商混淆了。 *是撤消操作符。 – cheznead

回答

55

引用表示將現有變量的地址(使用&)設置爲指針變量。 爲了有效,指針必須被設置爲相同的類型作爲指針的變量的地址,沒有星號:

int c1; 
int* p1; 
c1 = 5; 
p1 = &c1; 
//p1 references c1 

解引用一個指針指使用運算符*(星號字符)來訪問存儲在指針處的值: 注意:存儲在指針地址處的值必須是「同一類型」的值,作爲指針「指向」的變量的類型,但存在不能保證除非指針設置正確,否則就是這種情況。指針指向的變量類型是最少的星號。

int n1; 
n1 = (*p1); 

無效解引用可能會或可能不會導致死機:

  • 任何未初始化的指針的任何解引用可以導致崩潰
  • 具有無效類型轉換解引用將不得不導致崩潰的可能性。
  • 解引用一個指針,指向這是動態分配的,並隨後解除分配可導致崩潰
  • 解引用一個指針自超出範圍也可以導致崩潰的變量的變量。

無效引用更可能導致編譯器錯誤不是崩潰,但它不依賴於編譯器爲這是一個好主意。

參考文獻:

http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators

& is the reference operator and can be read as 「address of」. 
* is the dereference operator and can be read as 「value pointed by」. 

http://www.cplusplus.com/doc/tutorial/pointers/

& is the reference operator  
* is the dereference operator 

http://en.wikipedia.org/wiki/Dereference_operator

The dereference operator * is also called the indirection operator. 
13

我一直聽說它們在相反的意義上使用:

  • &是參考操作員 - 它給你一個參考(指針)的一些對象

  • *是引用操作 - 它需要一個參考(指針)並將您提交回的對象;

8

一開始,你有他們倒退:&是參考和*就是廢棄。

引用一個可變裝置訪問所述變量的存儲器地址:解引用可變裝置訪問存儲在一個存儲器地址的變量

int i = 5; 
int * p; 
p = &i; //&i returns the memory address of the variable i. 

int i = 5; 
int * p; 
p = &i; 
*p = 7; //*p returns the variable stored at the memory address stored in p, which is i. 
//i is now 7 
+2

等待,變量i的內存地址不是5,5是i的值。不是嗎?內存地址應該是類似.. 0XA234948 ...我們不需要知道。 – Nayana

+0

@dockbudu正確。 i的值是5,內存地址將是我們無法控制的一些值(通常以十六進制表示)。 – ApproachingDarknessFish

4

找到以下解釋:

int main() 
{ 
    int a = 10;// say address of 'a' is 2000; 
    int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000 
    int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10. 
} 

結論:

  1. & [地址操作]用於參考。
  2. * [星號運算符]用於解引用。