Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display a pointer address in C#?

I've not done any pointers since I've been programming in C# - and my C++ days were long ago. I thought I should refresh my knowledge and was just playing around with them because of another question on here. I understand them all okay, but I can't figure out how to write the pointer's address to the console...

char c = 'c';
char d = 'd';
char e = 'e';

unsafe
{
    char* cp = &d;
    //How do I write the pointer address to the console?
    *cp = 'f';
    cp = &e;
    //How do I write the pointer address to the console?
    *cp = 'g';
    cp = &c;
    //How do I write the pointer address to the console?
    *cp = 'h';        
}
Console.WriteLine("c:{0}", c); //should display "c:h";
Console.WriteLine("d:{0}", d); //should display "d:f";
Console.WriteLine("e:{0}", e); //should display "e:g";

Using Console.WriteLine(*cp); gives me the current value at the pointer address... what if I want to display the actual address?

like image 261
BenAlabaster Avatar asked Jan 13 '10 14:01

BenAlabaster


People also ask

How do you print the address of a pointer in C?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

How do I find the address of a pointer?

Using a Pointer: To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.

Do pointers have addresses in C?

The Pointer in C, is a variable that stores address of another variable. A pointer can also be used to refer to another pointer function. A pointer can be incremented/decremented, i.e., to point to the next/ previous memory location.


2 Answers

Console.WriteLine(new IntPtr(cp));
like image 189
Darin Dimitrov Avatar answered Sep 22 '22 18:09

Darin Dimitrov


Remember that with managed code the garbage collector is free to move things around on you. Make sure to pin your object down if your in a situation where the address matters.

like image 23
Joel Coehoorn Avatar answered Sep 19 '22 18:09

Joel Coehoorn