sizeof

本文详细介绍了C#中sizeof运算符的使用方法,包括其语法、限制条件及如何应用于不同值类型。此外,还通过示例解释了结构体大小计算的原则,并解答了关于结构体大小的一些常见疑问。

The sizeof operator is used to obtain the size in bytes for a value type. A sizeof expression takes the form:

sizeof(type)

where:

type
The value type for which the size is obtained.
Remarks

The sizeof operator can be applied only to value types, not reference types.  

The sizeof operator can only be used in the unsafe mode.

The sizeof operator cannot be overloaded.

Example
// cs_operator_sizeof.cs
// compile with: /unsafe

// Using the sizeof operator
using System;
class SizeClass 
{
   // Notice the unsafe declaration of the method:
   unsafe public static void SizesOf() 
   {
      Console.WriteLine("The size of short is {0}.", sizeof(short));
      Console.WriteLine("The size of int is {0}.", sizeof(int));
      Console.WriteLine("The size of long is {0}.", sizeof(long));
   }
}

class MainClass 
{
   public static void Main() 
   {
      SizeClass.SizesOf();
   }
}
Output
The size of short is 2.
The size of int is 4.
The size of long is 8. 
sizeof 只可以用与value type 
reference type 大小呢?

struct Struct1 { }
        struct Struct2 { long l;}
        struct Struct3 { byte b;}
        struct Struct4 { long l; byte b;}
        unsafe static void Main(string[] args)
        {
            Console.WriteLine(sizeof(Struct1) + "、" + sizeof(Struct2) + "、" + sizeof(Struct3) + "、" + sizeof(Struct4));
            Console.ReadLine();
        }

结果是:1、8、1、16
Struct1是空的,sizeof(Struct1)为什么不是0?
如果struct本身占1字节那么Struct2为什么不是1+8=9?
如果如Struct2、Struct3所示,struct占用字节数只取决于其中的字段,为什么Struct4不是8+1=9?
给结构加上这个属性就行了:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
`sizeof` 是C语言中一个非常有用的运算符,用于在编译时计算数据类型或变量的大小 [^1]。 ### 使用方法 - **计算数据类型大小**:可以直接对数据类型使用 `sizeof` 运算符,例如 `sizeof(int)` 会返回 `int` 类型在当前平台上所占用的字节数。代码示例如下: ```c #include <stdio.h> int main() { printf("Size of int: %zu bytes\n", sizeof(int)); return 0; } ``` - **计算变量大小**:也可以对变量使用 `sizeof` 运算符,比如定义一个 `int` 类型的变量 `num`,`sizeof(num)` 能得到该变量占用的字节数。代码示例如下: ```c #include <stdio.h> int main() { int num = 10; printf("Size of num: %zu bytes\n", sizeof(num)); return 0; } ``` - **在结构体定义中的应用**:在定义一个结构体时,可以使用 `sizeof` 函数获取结构体的大小,以便在后续的程序中添加新的成员变量时,不会影响已有的成员变量的内存布局 [^2]。代码示例如下: ```c #include <stdio.h> struct Example { int a; char b; }; int main() { struct Example ex; printf("Size of struct Example: %zu bytes\n", sizeof(ex)); return 0; } ``` ### 原理 `sizeof` 是在编译时计算的,而不是在运行时执行。编译器通过分析变量或类型来确定其在目标平台上所占用的内存大小。由于 `sizeof` 是在编译时计算的,因此它通常不会引入任何运行时开销 [^3]。 在C++中,借助“编译时常量”,还可在模板或类定义阶段进行尺寸检查,示例代码如下: ```cpp template <typename T> void check_alignment() { static_assert(sizeof(T) % alignof(T) == 0, "类型 T 大小必须是其对齐方式的整数倍"); } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值