指针:算术运算
本主题讨论使用算术运算符 + 和 - 来操作指针。
![]() |
---|
不能对 void 指针执行任何算术运算。 |
本在线速查手册由www.w▫3▫x▫u▫e.com提供,请勿盗用!
对指针执行加减数值操作
可以将类型为
指针相减
也可以对相同类型的指针进行减法运算。计算结果的类型始终为 long。例如,如果 p1 和 p2 都是类型为 pointer-type* 的指针,则表达式 p1-p2 的计算结果为:
((long)p1 - (long)p2)/sizeof(pointer_type)
当算术运算溢出指针范围时,不会产生异常,并且结果取决于具体实现。
示例
C# | |
---|---|
// compile with: /unsafe |
本在线速查手册由www.w▫3▫x▫u▫e.com提供,请勿盗用!
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 |
本在线速查手册由www.w▫3▫x▫u▫e.com提供,请勿盗用!