Consider the following code:
-
C # code
-
unsafe { byte b = 3; double d = 10.0; int i = 5; byte* pb = &b; double* pd = &d; int* pi = &i; Console.WriteLine("Address of b is 0x{0:X},size is {1},value is {2}", (uint)pb, sizeof(byte), b); Console.WriteLine("Address of d is 0x{0:X},size is {1},value is {2}", (uint)pd, sizeof(double), d); Console.WriteLine("Address of i is 0x{0:X},size is {1},value is {2}", (uint)pi, sizeof(int), i); Console.WriteLine("Address of pb is 0x{0:X},size is {1},value is 0x{2:X}", (uint)&pb, sizeof(byte*), (uint)pb); Console.WriteLine("Address of pd is 0x{0:X},size is {1},value is 0x{2:X}", (uint)&pd, sizeof(double*), (uint)pd); Console.WriteLine("Address of pi is 0x{0:X},size is {1},value is 0x{2:X}", (uint)&pi, sizeof(int*), (uint)pi); }
The output result displayed on my host is
Address of B is 0x12f46c, size is 1, value is 3
Address of D is 0x12f464, size is 8, value is 10
Address of I is 0x12f460, size is 4, value is 5
Address of Pb is 0x12f45c, size is 4, value is 0x12f46c
Address of PD is 0x12f458, size is 4, value is 0x12f464
Address of PI is 0x12f454, size is 4, value is 0x12f460
Now my problem is: Looking at the code, the stack should be filled down from the high address to the low address, and the byte only occupies 1 byte, the memory block of the 32-bit processor system stack is always allocated in multiples of 4 bytes. The address of B is 0x12f46c, so the value of B should be stored in 0x12f468 ~ 0x12f46b occupies 4 bytes, and then allocates memory for D. The double type occupies 8 bytes, and its address should be 0x12f468. D should be stored in 0x12f460 ~ In 0x12f467, why does output result B occupy 8 bytes of memory while D occupies only 4 bytes of memory.
In addition, if you remove the last three lines of code
-
C # code
-
unsafe { byte b = 3; double d = 10.0; int i = 5; byte* pb = &b; double* pd = &d; int* pi = &i; Console.WriteLine("Address of b is 0x{0:X},size is {1},value is {2}", (uint)pb, sizeof(byte), b); Console.WriteLine("Address of d is 0x{0:X},size is {1},value is {2}", (uint)pd, sizeof(double), d); Console.WriteLine("Address of i is 0x{0:X},size is {1},value is {2}", (uint)pi, sizeof(int), i);}
The output result is
Address of B is 0x12f45c, size is 1, value is 3
Address of D is 0x12f460, size is 8, value is 10
Address of I is 0x12f468, size is 4, value is 5
Memory Allocation is changed from low address to high address, but B occupies 4 bytes and D occupies 8 bytes. What is the solution?