2011-07-08 73 views
2

假設我有一個byte []數組,我想知道什麼,我真的這樣做時,我做的指針數組,然後將其轉換爲int。當我取消引用說INT指針,我得到的情況下波紋管數量較多:(代碼可能有錯誤)基本鑄造的問題(C#)

byte[] bytes = new byte[100]; 
    bytes[0] = 1; 
    bytes[1] = 2; 
    bytes[2] = 3; 
    bytes[3] = 4; 


    fixed (byte* pMem = &bytes[0]) 
    { 

    Debug.WriteLine("{0:x16}", (int)pMem); 

    byte* pMemPlus1 = pMem + 1; 
    Debug.WriteLine("{0:x8}", *pMemPlus1); 

    byte* pMemPlus2 = pMem + 2; 
    Debug.WriteLine("{0:x16}", *pMemPlus2); 

    int* pArrayBase = (int*) pMem; 
    Debug.WriteLine("{0:x8}", *pArrayBase); 

    int* pArrayBasePlus1 = pArrayBase+1; 
    Debug.WriteLine("{0:x8}", *pArrayBasePlus1; 
    } 

權,從而預期值Pmem,PMemPlus1和PMemPlus2提領1,2和3(詮釋)pMem我拿它是指針(內存地址)的值。

但是,當它作爲一個int指針強制轉換時,pArrayBase給出了4030201,pArrayBasePlus1給出了數字4.後者是有意義的,因爲int是4個字節長。但我不明白。當我只取消引用int-cast數組指針(pArrayBase)時的結果。任何解釋?我可能無法理解正確投射的概念。

+0

這是很容易創建的代碼,由於轉換錯誤故障,如果你把它寫在C.不要讓生活困難的自己,如果這是你的目標。用較少的諷刺(不難實現),你爲什麼要演員? –

+0

基本上我一直在經歷本教程:geekswithblogs.net/robp/archive/2008/08/13/speedy-c-part-3-understanding-memory-references-pinned-objects-and.aspx –

+2

注意,鑄造指向int的指針在32位機器上只是一個明智的事情。如果你有一個64位的進程,那麼你必須投入很長時間。你可能會考慮鑄造IntPtr的,這是保證是大小爲指針同一個結構。 –

回答

1

你的內存是奠定了類似以下內容:

01 02 03 04 00 00 00 00 

pArrayBase指向你的數組的基址的四字節整數。因爲整數存儲在小端格式,這導致了價值0x04030201。有趣的結果是,當您解除引用pArrayBasePlus1時。 pArrayBasePlus1指向前四個字節後面的四個字節。除非你忽略了一些代碼,它看起來像* pArrayBasePlus1應該是0

+0

謝謝,我需要仰視字節順序等是我的代碼是有點錯了,你是正確的,* pArrayBasePlus1爲零。 –