zoukankan      html  css  js  c++  java
  • C#操作指针

    如何:递增和递减指针

    使用增量和减量运算符 ++ 和 -- 可以将 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
        }
    }
  • 相关阅读:
    Junit初级编码(一)第一个Junit测试程序
    关于健身与健美
    spring入门(一)
    HTTP状态301、404、200、304分别表示什么意思
    预处理prepareStatement是怎么防止sql注入漏洞的?
    详解SESSION与COOKIE的区别
    Form表单中method为get和post的区别
    tomcat服务器配置及使用
    ubuntu 14.04 安装mysql server初级教程
    《电路学习第三天》 之 线性稳压电源的设计
  • 原文地址:https://www.cnblogs.com/2Yous/p/4888492.html
Copyright © 2011-2022 走看看