Unsafe C # code snippet with pointers

I came across the following piece of code and had to predict the output. My answer was 220, but he was told about his wrongness. Can someone tell me the correct result and explain why.

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

EDIT: Thanks to everyone for the explanatory answers. The correct answer is definitely 220 if and only if the above block of code (which is C # code, sorry for not mentioning this in the question) was declared unmanageable. Thanks for all your answers. Each of them was really informative and helpful.

+3
source share
4 answers

The answer is that it does not compile. You will get the following error:

CS0214:

, , :

int ptr1 = 0;

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

Console.WriteLine(ptr1);

220.

, :

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

: /unsafe switch ( " " Visual Studio)

. Pointer fun with binky , , .

+6

220, - # ( ++)

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.

;)

+5

I don't know anything about pointers to C #, but I can try to explain what it does in 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);
}
+3
source

@Zaki: you need to mark your build to allow unsafe code and block your unsafe code as follows:

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);
    }
}

Honestly, I never used pointers to C # (never used).

I did a quick google search and found this , which helped me create the above example.

+1
source

Source: https://habr.com/ru/post/1712597/


All Articles