-4
bool b;
unsafe
{    
    bool* p1 = &b; 
    Console.WriteLine("p1: {0}", p1->ToString());
}

Gives me

p1:false

But I want to print the address. How can I do it?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173
  • Try to search first. – CodeCaster Jan 23 '15 at 13:14
  • The output is not really surprising: After all, you are dereferencing (`->`) a `bool*`, so you get back a `bool`, then you call `ToString` on *that*. Not sure if you can print out a `bool*`. Off-topic: Since object addresses could change due to the garbage collector, perhaps look into the [`GCHandle`](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.aspx) type and specifically [`GCHandle.AddrOfPinnedObject`](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.addrofpinnedobject.aspx). – stakx - no longer contributing Jan 23 '15 at 13:14
  • 1
    possible duplicate of: http://stackoverflow.com/q/2057469/1552016 – qqbenq Jan 23 '15 at 13:15
  • * dereferences a pointer. to call a Method from the pointing object, you have to dereference it. you can call the method like this: (*pointer).Method(), or do it like this pointer->Method() – Jens Jan 23 '15 at 13:17

1 Answers1

3
using System;

namespace Test81
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            bool b;
            unsafe
            {    
                bool* p1 = &b; 
                Console.WriteLine("p1: 0x{0:X}", new IntPtr(p1).ToInt64());
            }
        }
    }
}
luk32
  • 15,812
  • 38
  • 62