怪奇物语

怪奇物语

首页 新随笔 联系 管理

结构体成员定义的顺序也会影响结构体的大小,内存对齐,内存填充

using System;
using System.Runtime.InteropServices;

struct StrcutOne
{
    public int b; // 4 bytes
    public byte a; // 1
    public byte c; // 1
    // 4+1+1+2(在填充两个2个字节) = 8 字节
}

struct StrcutTwo
{
    public byte a; // 1 byte
    public int b; // 4 bytes
    public byte c; // 1 byte
    // 1+3(填充)+4+1+3(填充) = 12
}

class Program
{
    static void Main()
    {
        Console.WriteLine($"Size of ChangedOrder: {Marshal.SizeOf<StrcutOne>()} bytes");
        Console.WriteLine($"Size of ExampleStruct: {Marshal.SizeOf<StrcutTwo>()} bytes");
    }
}
posted on 2024-09-07 14:51  超级无敌美少男战士  阅读(52)  评论(0)    收藏  举报