更新:2007 年 11 月
本主题讨论使用算术运算符 + 和 - 来操作指针。
说明: |
---|
不能对 void 指针执行任何算术运算。 |
对指针执行加减数值操作
可以将类型为
指针相减
也可以对相同类型的指针进行减法运算。计算结果的类型始终为 long。例如,如果 p1 和 p2 都是类型为 pointer-type* 的指针,则表达式 p1-p2 的计算结果为:
((long)p1 - (long)p2)/sizeof(pointer_type)
当算术运算溢出指针范围时,不会产生异常,并且结果取决于具体实现。
示例
C# | 复制代码 |
---|---|
// compile with: /unsafe
|
C# | 复制代码 |
---|---|
class PointerArithmetic { unsafe static void Main() { int* memory = stackalloc int[30]; long* difference; int* p1 = &memory[4]; int* p2 = &memory[10]; difference = (long*)(p2 - p1); System.Console.WriteLine("The difference is: {0}", (long)difference); } } // Output: The difference is: 6 |
C# 语言规范
有关更多信息,请参见 C# 语言规范 中的以下各章节:
18.5.6 指针算法