I came across the following code snippet and needed to predict the output. My answer was 220 but was told its wrong. Could someone tell me the correct output and please explain why.
using System;
class pointer
{
public static void Main()
{
int ptr1=0;
int* ptr2=&ptr1;
*ptr2=220;
Console.WriteLine(ptr1);
}
}
EDIT:
Thank you everybody 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 it in the question) was declared as unmanaged. Thank you for all your answers. Every one of em was really informative and helpful.
The answer is that it does not compile. You will get the following error:
error CS0214: Pointers and fixed size buffers may only be used in an unsafe contex
If, however, you write this:
Then you will indeed get 220.
You can also create an entire unsafe method, rather than creating specific unsafe blocks:
Note: you also have to compile with the /unsafe switch (check “Allow unsafe code” in the project properties in Visual Studio)
Edit: Have a look at Pointer fun with binky for a short, funny, yet informative video on pointers.