码迷,mamicode.com
首页 > Windows程序 > 详细

C#操作指针

时间:2015-10-17 23:27:57      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

如何:递增和递减指针

使用增量和减量运算符 ++ 和 -- 可以将 pointer-type* 类型的指针的位置改变 sizeof (pointer-type)。 增量和减量表达式的形式如下:

++p;
p++;
--p;
p--;

增量和减量运算符可应用于除 void* 类型以外的任何类型的指针。

pointer-type 类型的指针应用增量运算符的效果是将指针变量中包含的地址增加 sizeof (pointer-type)。

pointer-type 类型的指针应用减量运算符的效果是从指针变量中包含的地址减去 sizeof (pointer-type)。

当运算溢出指针范围时,不会产生异常,实际结果取决于具体实现。

此示例通过将指针增加 int 的大小来遍历一个数组。 对于每一步,此示例都显示数组元素的地址和内容。

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);
            }
        }
    }
}
//Output--------------------
Value:0 @ Address:12860272
Value:1 @ Address:12860276
Value:2 @ Address:12860280
Value:3 @ Address:12860284
Value:4 @ Address:12860288

指针的算术运算

本主题讨论使用算术运算符 + 和 - 来操作指针。不能对 void 指针执行任何算术运算。

可以将类型为 intuintlongulong 的值 n 与 void* 以外任何类型的指针 p 和 相加。 结果 p+n 是加上 n * sizeof(p) to the address of p 得到的指针。

同样,p-n 是从 p 的地址中减去 n * sizeof(p) 得到的指针。

 

也可以对相同类型的指针进行减法运算。 计算结果的类型始终为 long。 例如,如果 p1 和 p2 都是类型为 pointer-type* 的指针,则表达式 p1-p2 的计算结果为:

((long)p1 - (long)p2)/sizeof(pointer_type)

当算术运算溢出指针范围时,不会产生异常,并且结果取决于具体实现。

class PointerArithmetic
{
    unsafe static void Main() 
    {
        int* memory = stackalloc int[30];
        long difference;
        int* p1 = &memory[4];
        int* p2 = &memory[10];

        difference = p2 - p1;

        System.Console.WriteLine("The difference is: {0}", difference);
    }
}
// Output:  The difference is: 6

 指针比较

可应用下面的运算符比较任意类型的指针:

==   !=   <   >   <=   >=

比较运算符比较两个操作数的地址,就像他们是无符号整数一样

class CompareOperators
{
    unsafe static void Main() 
    {
        int x = 234;
        int y = 236;
        int* p1 = &x;
        int* p2 = &y;

        System.Console.WriteLine(p1 < p2);//True
        System.Console.WriteLine(p2 < p1);//False
    }
}

 

C#操作指针

标签:

原文地址:http://www.cnblogs.com/2Yous/p/4888492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!