Why does my structure go to an unexpected size when I have a double?

public struct TestStruct
{
    public int first;
    public int second;
    public int third;
}

Marshal.SizeOf returns 12, which I assume, because ints are 4 bytes each. If I changed the third to double instead of int, I would expect Marshal.SizeOf to return 16. This is so. But if I added a fourth, which was double, Marshal.SizeOf would return 24 when I expect 20. I could have 10 integers, and in the end, each would have 4 bytes each. But if I add a double number after three ints, the size is not as expected.

public struct TestStruct //SizeOf 12
{
    public int first;
    public int second;
    public int third;
}  

public struct TestStruct //SizeOf 16
{
    public int first;
    public int second;
    public double third;
}  

public struct TestStruct //SizeOf 24, but I feel like it should be 20
{
    public int first;
    public int second;
    public double third;
    public int fourth;
}

Where did my thinking lead me astray?

+5
source share
3 answers

In addition to JimR's answer, you can explicitly change this behavior using the StructLayout attribute:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct TestStruct // sizeof is now 20
{
    public int first;
    public int second;
    public double third;
    public int fourth;
}

, 1, , . Pack 0 ( ) .. ( 2) . , .. .

. MSDN: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.pack.aspx

+8

- , .

- . , , int, 4 . 2 , int .

int, float double , SSE Intel.

+5

, .

, , #, :

[StructLayout(LayoutKind.Sequential)]

LayoutKind.Sequential, :

LayoutKind

, , . , StructLayoutAttribute.Pack, .

:

[StructLayout(LayoutKind.Auto)]

, - 20.

+4

All Articles