开发者

Basic casting question (C#)

Suppose I have a byte[] array, I am wondering what I am really doing when I make a pointer to the array and then cast it to an int. When I dereference the said int pointer, I get a larger number in the case bellow: (code may have errors)

    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;
    }   

Right so as expected, pMem, PMemPlus1 and PMemPlus2 de开发者_JAVA技巧reference to 1,2 and 3. (int)pMem I take it is the value of the pointer (memory address).

When it is cast as an int pointer though, pArrayBase gives 4030201 and pArrayBasePlus1 gives the number 4. The latter makes sense because an int is 4 bytes long, right. But I don't understand. the result when I just dereference the int-cast array pointer (pArrayBase). Any explanations? I might not understand the concept of casting properly.


Your memory is layed out something like the following:

01 02 03 04 00 00 00 00

pArrayBase is pointing to the four-byte integer at your array's base address. Since integers are stored in little endian format, this results in the value 0x04030201. The interesting result is when you dereference pArrayBasePlus1. pArrayBasePlus1 is pointing to the four bytes following the first four. Unless you've left out some code, it looks like *pArrayBasePlus1 should be 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜