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?
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.
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.
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.
Console.WriteLine(new IntPtr(cp));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With