2012-02-29 99 views
1

我想了解指針和數組。奮力網上找到指針(雙關語!)之後,我說明我的困惑在這裏..指針和數組混淆

//my understanding of pointers 
int d = 5; //variable d 
int t = 6; //variable t 

int* pd; //pointer pd of integer type 
int* pt; //pointer pd of integer type 

pd = &d; //assign address of d to pd 
pt = &t; //assign address of d to pd 

//*pd will print 5 
//*pt will print 6 

//My understanding of pointers and arrays 

int x[] = {10,2,3,4,5,6}; 
int* px; //pointer of type int 

px = x; //this is same as the below line 
px = &x[0]; 
//*px[2] is the same as x[2] 

到目前爲止,我得到它。現在,當我執行以下操作並打印pd [0]時,它會顯示出類似-1078837816的內容。這裏發生了什麼?

pd[0] = (int)pt; 

任何人都可以幫忙嗎?

回答

1

INT *磅;是一個指向整數類型變量的指針,它不是一個整數。通過指定(int)pt,您告訴編譯器將typecast pt設置爲整數。

要獲得pt處的變量,您可以使用* pt,這會返回存儲在pt中的地址指向的整數變量。

因爲你說pd [0],而pd不是數組,所以有點令人困惑。

+0

在這種情況下,我在閱讀:「http://www.osdever.net/tutorials/view/implementing-basic-paging」。 「設置頁表」部分聲明一個無符號的long * page_table,然後在for循環中使用page_table [i]。但page_table不是一個數組,所以我很困惑,爲什麼它會這樣使用。你能解釋一下嗎? – rgamber 2012-02-29 06:59:30

+1

數組本質上是指向順序存儲器的指針,數組中的每個元素都是指針變量類型的大小。在那個例子中,他們創建了一個從內存中的特定點開始的無符號長指針(4字節),然後循環1024次,基本上覆蓋了4096字節的內存。數組的每個增量都是內存中的下一個無符號長整數。 – 2012-02-29 07:05:00

+0

對不起,但我很困惑,如何將無符號長指針變量用作數組。你說「數組的每個增量是內存中的下一個無符號long」,但是這裏沒有聲明數組。謝謝您的幫助。 – rgamber 2012-02-29 07:15:07

1

您已經告訴編譯器將指針pt的字節解釋爲int,因此您將看到一個看似隨機的結果,表示pt碰巧位於內存中的任何位置。

我想你想

pd[0] = pt[0] 

pd[0] = *pt;