代码之家  ›  专栏  ›  技术社区  ›  Zak

带有指针的不安全代码段

  •  3
  • Zak  · 技术社区  · 15 年前

    我遇到了下面的代码片段,需要预测输出。我的答案是220,但被告知是错误的。有人能告诉我正确的输出并解释原因吗?

    using System;
    class pointer
    {
      public static void Main()
      {
       int ptr1=0;
       int* ptr2=&ptr1;
       *ptr2=220;
       Console.WriteLine(ptr1);
      }
    }
    

    编辑: 谢谢大家的解释性回答。如果并且仅当上述代码块(即C代码,抱歉在问题中没有提到它)被声明为非托管时,正确的答案肯定是220。谢谢你的回答。他们中的每一个人都非常有用。

    4 回复  |  直到 15 年前
        1
  •  6
  •   IRBMe    15 年前

    答案是它不编译。您将得到以下错误:

    错误CS0214:指针和固定大小的缓冲区只能在不安全的上下文中使用

    但是,如果您写下:

    int ptr1 = 0;
    
    unsafe {
        int* ptr2 = &ptr1;
        *ptr2 = 220;
    }
    
    Console.WriteLine(ptr1);
    

    这样你就可以得到220英镑。

    您还可以创建一个完整的不安全方法,而不是创建特定的不安全块:

    public unsafe void Something() {
        /* pointer manipulation */
    }
    

    注释 :您还必须使用/unsafe开关进行编译(在Visual Studio的项目属性中选中“允许不安全代码”)。

    编辑 :看看 Pointer fun with binky 一个简短,有趣,但信息丰富的视频指针。

        2
  •  5
  •   Yvo    15 年前

    结果是220,下面是一个C代码代码片段来测试它(这里没有C++)

    using System;
    
    internal class Pointer {
        public unsafe void Main() {
            int ptr1 = 0;
            int* ptr2 = &ptr1;
            *ptr2 = 220;
    
            Console.WriteLine(ptr1);
        }
    }
    

    步骤:

    • ptr1的赋值为0
    • ptr2指向ptr1的地址空间
    • ptr2的赋值为220(但指向ptr1的地址空间)
    • 所以当现在请求ptr1时,值也是220。

    请你的老师也给我一个A;)

        3
  •  3
  •   Treb    15 年前

    我对C语言中的指针一无所知,但我可以尝试解释它在C/C++中的作用:

    public static void Main()
    {
      // The variable name is misleading, because it is an integer, not a pointer
      int ptr1 = 0;
    
      // This is a pointer, and it is initialised with the address of ptr1 (@ptr1)
      // so it points to prt1.
      int* ptr2 = &ptr1;
    
      // This assigns to the int variable that ptr2 points to (*ptr2,
      // it now points to ptr1) the value of 220
      *ptr2 = 220;
    
      // Therefore ptr1 is now 220, the following line should write '220' to the console
      Console.WriteLine(ptr1);
    }
    
        4
  •  1
  •   Zack    15 年前

    @扎基:你需要标记你的程序集以允许不安全的代码,并像这样屏蔽不安全的代码:

    public static class Program {
        [STAThread()]
        public static void Main(params String[] args) {
            Int32 x = 2;
            unsafe {
                Int32* ptr = &x;
                Console.WriteLine("pointer: {0}", *ptr);
    
                *ptr = 400;
                Console.WriteLine("pointer (new value): {0}", *ptr);
            }
            Console.WriteLine("non-pointer: " + x);
    
            Console.ReadKey(true);
        }
    }
    

    老实说,我从来没有用过C中的指针(从来没有用过)。

    我做了一个快速 Google Search 发现 this 这帮助我产生了上面的例子。