开发者

How int* is bool in C#?

I am trying to use pointers in C# like in C.

public static void Main(string[] args)
    {
        unsafe
        {
            int i = 5;
            int* j = &i;
            Console.WriteLine(j);  //cannot convert from 'int*' to 'bool'
        } 

    }
开发者_如何学Go

I have two queries regarding this code:

  1. How to compile with /unsafe ?
  2. Why Console.Writeline(j) is trying to convert j to bool?


Point 2) takes 2 steps:

  • Console.WriteLine() does not have an overload for int*
  • Apparently it then tries it's first overload, WriteLine(bool value) and cannot find a conversion

I would call this a weak error report.

To print the address, cast it to an ulong first.


  1. If using csc, add /unsafe; or in a vs project, go to project properties and there is a checkbox
  2. Simply it can't find a better match; I'd have to check the spec for the exact order rules, but just treat it as the compiler saying "no suitable match, I'm guessing at this but this doesn't work either"


Writing the value of the pointer is pointless, it is just a random address. You initialize the pointer with the address of a variable on the stack, such an address doesn't repeat well. You want to dereference the pointer with the * operator. Like this:

        Console.WriteLine(*j);

Which writes the pointed-to value, 5 in your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜