使用增量和减量运算符 ++ 和 -- 可以将 pointer-type* 类型的指针的位置改变 sizeof (pointer-type)。增量和减量表达式的形式如下:
参数
-
p
-
指针变量。
-
++
-
增量运算符。
-
--
-
减量运算符。
备注
示例
此示例通过将指针增加 int 的大小来遍历一个数组。对于每一步,此示例都显示数组元素的地址和内容。
C# | 复制代码 |
---|
// compile with: /unsafe
|
C# | 复制代码 |
---|
class IncrDecr
{
unsafe static void Main()
{
int[] numbers = {0,1,2,3,4};
// Assign the array address to the pointer:
fixed (int* p1 = numbers)
{
// Step through the array elements:
for(int* p2=p1; p2<p1+numbers.Length; p2++)
{
System.Console.WriteLine("Value:{0} @ Address:{1}", *p2, (long)p2);
}
}
}
}
|
示例输出
Value:0 @ Address:12860272
Value:1 @ Address:12860276
Value:2 @ Address:12860280
Value:3 @ Address:12860284
Value:4 @ Address:12860288
请参见