In Delphi:
How do I get the address (0x2384293) a pointer points to?
var iValue := Integer;
iptrValue := PInteger;
implementation
procedure TForm1.Button1Click(Sender: TObject);
begin
iptrValue := @iValue;
iValue := 32342;
//Should return the same value:
Edit1.Text := GetAddressOf(iptrValue);
Edit2.Text := GetAddressOf(iValue);
So what is GetAddress in reality :)
To get the address of something, use the @
operator or the Addr
function. You've already demonstrated correct use of that. You got the address of iValue
and stored it in iptrValue
.
To display an address, you can use the Format
function to convert a pointer value into a string. Use the %p
format string:
Edit1.Text := Format('%p -> %p -> %d', [@iptrValue, iptrValue, iptrValue^]);
That will display the address of the iptrValue
variable, then the address stored in that variable, and then the value stored at that address.
The iptrValue
variable declaration reserves some bytes in memory and associates a name with them. Suppose the address of the first byte is $00002468
:
iptrValue
┌──────────┐
$2468: │ │
└──────────┘
The iValue
declaration reserves another piece of memory, and it will probably be adjacent to the previous declaration's memory. Since iptrValue
is four bytes wide, the address of iValue
would be $0000246C
:
iValue
┌──────────┐
$246c: │ │
└──────────┘
The boxes I've drawn are empty for now because we haven't discussed what values those variables hold. We've only discussed the variables' addresses. Now to the executable code: You write @iValue
and store the result in iptrValue
, so you get this:
iptrValue
┌──────────┐
$2468: │ $246c ├─────╮
└──────────┘ │
iValue │
┌──────────┐ │
$246c: │ │←────╯
└──────────┘
Next, you assign 32342 to iValue
, so your memory looks like this:
iptrValue
┌──────────┐
$2468: │ $246c ├─────╮
└──────────┘ │
iValue │
┌──────────┐ │
$246c: │ 32342 │←────╯
└──────────┘
Finally, when you display the results of the Format
function from above, you would see this value:
00002468 -> 0000246C -> 32342