2014-10-18 17 views
0
#include<stdio.h> 

int main() 
{ 
    int z; int **x; int *y; 
    x = (int **) malloc(sizeof(int*)); 
    *x = malloc(sizeof(int)); 
    **x = 5; 
    y = *x; //POINT 1 
    z = 3; 
    *x = &z;//POINT 2 
    printf("%d\n",*y); 
    printf("%d\n", **x); 
    **x = 2; 
    printf("%d\n",*y); 
    *y=1; 
    printf("%d\n",z); 
} 

輸出我得到的是如下意外的輸出與C指針和間接的水平

5 //這是爲什麼5?

我的問題是不是應該在第一輸出打印3?爲什麼5打印?

我的問題是這個程序產生搖晃的引用或垃圾?我想這可能是這種意外產出的原因之一。有人可以請解釋。

+0

縮進你的代碼 – Soren 2014-10-18 21:04:33

+0

不,你的程序僅僅是泄漏內存,但它並沒有寫入到未分配的內存也不會導致懸擺指針。 – 2014-10-18 21:08:25

+0

另外,我不明白爲什麼第一個應該打印'3'。你需要**認爲**指針是什麼。指針本身存儲在內存中。它們可以像它們指向的對象一樣複製和傳遞(在這種情況下爲'int's)。此外,您需要了解指針**不是引用。** – 2014-10-18 21:10:29

回答

4

讓我們畫出來。

後初始化x*x**x你的內存看起來是這樣的:

 
+---+  +----+  +---+ 
| x | --> | *x | --> | 5 | 
+---+  +----+  +---+ 

的分配y

 
+---+  +----+ 
| x | --> | *x | --\ 
+---+  +----+ \  +---+ 
        >--> | 5 | 
      +---+ / +---+ 
      | y | --/ 
      +---+ 

然後你讓*x點別的地方,所以你必須這個:

 
+---+  +----+  +---+ 
| x | --> | *x | --> | z | 
+---+  +----+  +---+ 

+---+  +---+ 
| y | --> | 5 | 
+---+  +---+ 

換句話說,你讓y指向*x指向的地方,而不是*x本身,所以當你改變*x指向的地方時,你不會改變y指向的地方。

+0

繪製指針只是瞭解它們的最好的東西。 +1 – 2014-10-18 21:12:40

+0

我的程序是否產生晃來晃去的參考或垃圾值? – user1010101 2014-10-18 21:12:45

+0

@ user2733436不,沒有懸掛指針或垃圾值。 – 2014-10-18 21:13:48

1

x指向指向內存位置的指針(如p)。您在該位置存儲值5
y指向指針p指向的位置,其值爲5的位置。
z是一個值爲3的內存位置。

現在使p指向z的存儲位置。但是這不是更改,其中y指向。因此它仍然指向價值爲5的位置。

1

在你的程序中你有y = *x;它把x指向的指針放入指針變量y中。 x中的指針指向的內存區域的值爲5,因爲y現在具有該指針,則* y現在爲5.然後,將新指針放入由x指向的指針區域中。

int main() 
{ 
    int z; int **x; int *y; 
    x = (int **) malloc(sizeof(int*)); // create a pointer to a pointer variable 
    *x = malloc(sizeof(int));   // create a pointer to an int that is put into the pointer that is pointed to by x (x -> int pointer -> int) 
    **x = 5;       // set the int value pointed to by the pointer that is pointed to by x to 5 
    y = *x; //POINT 1     // assign the pointer to the int value to another pointer variable 
    z = 3; 
    *x = &z;//POINT 2     // assign a new address to the pointer that is pointed to by x. 
    printf("%d\n",*y);    // print the value pointed to by y which is 5 
    printf("%d\n", **x);    // print the value that is pointed to by the pointer which is pointed to by x which is 3 
    **x = 2; 
    printf("%d\n",*y); 
    *y=1; 
    printf("%d\n",z); 
}