使用指针的不安全的C#代码片段

3
我看到了下面的代码片段并需要预测输出结果。我的答案是220,但被告知是错误的。请问有人能告诉我正确的输出结果并解释一下原因吗?
using System;
class pointer
{
  public static void Main()
  {
   int ptr1=0;
   int* ptr2=&ptr1;
   *ptr2=220;
   Console.WriteLine(ptr1);
  }
}

编辑: 感谢大家的解答。正确答案是220,但前提条件是上面这段代码(它是C#代码,抱歉在问题中没有提到)被声明为非托管代码。感谢所有的回答。每一个都非常有启发性和帮助。


2
这是否像不安全代码一样不安全地处理?在 C/C++ 中应该是220... - Daniel A. White
1
220,祝你完成作业的其余部分好运。 - Frank Schwieterman
1
这是使用不安全代码的C#。但是该代码应该被包装在一个不安全块中。 - Fredrik Mörk
5
由于您回答了220并且回答错误,显然希望的答案是它无法构建,因为您不在C#允许使用指针的不安全上下文中,比如这种情况。 - Greg D
1
+1 给出色的变量命名,ptr1 不是指针。 - Cade Roux
显示剩余2条评论
4个回答

6
答案是它无法编译。您将会得到以下错误信息:
错误 CS0214:指针和固定大小缓冲区只能在不安全的上下文中使用。
然而,如果您写成这样:
int ptr1 = 0;

unsafe {
    int* ptr2 = &ptr1;
    *ptr2 = 220;
}

Console.WriteLine(ptr1);

那么你确实会得到220。

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

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

注意:您还需要使用/unsafe开关进行编译(在Visual Studio中的项目属性中检查“允许不安全代码”)

编辑:观看指针玩乐趣,了解有关指针的简短、有趣且信息丰富的视频。


5
结果为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 吧 ;)


好的,第三行应该是“PTR2指向的位置上的整数被赋值为220”。PTR2的值(即PTR1的内存位置)并没有改变。 - darron
@Zyphrax:我把你的“步骤”部分复制到了一些文档中,以备将来使用。谢谢。 :) - Zack

3

我不知道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);
}

1

@Zaki:您需要标记您的程序集以允许不安全代码,并像这样阻止您的不安全代码:

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#中使用过指针(也从未有过使用的场景)。
我进行了一次快速的谷歌搜索,找到了这个,帮助我生成了上面的示例。

没问题 :) 我学到了新东西,很高兴分享。希望有人能够评估一下我的代码,并让我知道他们对它的看法。 :) - Zack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接