Address of a variable: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(45 intermediate revisions by 21 users not shown)
Line 9: Line 9:
===Get the Address===
===Get the Address===
To get the address of a variable, use <code>LA</code> (load address) instead of <code>L</code> (load):
To get the address of a variable, use <code>LA</code> (load address) instead of <code>L</code> (load):
<lang 360asm> LA R3,I load address of I
<syntaxhighlight lang="360asm"> LA R3,I load address of I
...
...
I DS F</lang>
I DS F</syntaxhighlight>


===Set the Address===
===Set the Address===
To set a variable dynamically at the same address of an other variable, use a <code>DSECT</code> (dummy section):
To set a variable dynamically at the same address of an other variable, use a <code>DSECT</code> (dummy section):
<lang 360asm> USING MYDSECT,R12
<syntaxhighlight lang="360asm"> USING MYDSECT,R12
LA R12,I set @J=@I
LA R12,I set @J=@I
L R2,J now J is at the same location as I
L R2,J now J is at the same location as I
Line 21: Line 21:
I DS F
I DS F
MYDSECT DSECT
MYDSECT DSECT
J DS F</lang>
J DS F</syntaxhighlight>
=={{header|8086 Assembly}}==
=={{header|6502 Assembly}}==
When programming in assembly language yourself, generally the addresses of variables are known in advance and chosen by the programmer rather than dynamically determined by the compiler. Loading values from RAM into memory requires the programmer to specify the address as the operand. This is true for zero-page memory, absolute memory addresses, and memory-mapped ports whose location is defined by the hardware manufacturer. Typically, the assembly programmer will use labels to ease this process, which get converted to memory addresses automatically when the program is assembled.
{{works with | https://www.dosbox.com/ | DOSBox}}


<syntaxhighlight lang="6502asm">;;;;;;; zero page RAM memory addresses
<lang asm>.model small
CursorX equ $00
CursorY equ $01
temp equ $02
;;;;;;; memory-mapped hardware registers
BorderColor equ $D020

Joystick1 equ $DC01
Joystick2 equ $DC00</syntaxhighlight>

Rather than setting the address of a variable, in assembly the programmer stores a calculated quantity in an address. The terms "memory address" and "variable" are often used interchangably.

<syntaxhighlight lang="6502asm">LDA #$20 ; load a constant into the accumulator

CLC
ADC #$50
ASL
SBC #$30 ; do some math

STA temp ; store the result in a temp variable (really a zero-page memory address).
</syntaxhighlight>

6502 assemblers treat a number without a # in front as a memory address.
<syntaxhighlight lang="6502asm">LDA #$30 ;load into the accumulator the constant value 0x30
LDA $30 ;load into the accumulator the value stored at memory address 0x0030.</syntaxhighlight>

The only exception to this rule is when defining bytes. These do not have # in front, but are treated as constants nonetheless:
<syntaxhighlight lang="6502asm">byte $30,$20,$10,$00 ;these are constant numeric values, not memory addresses.</syntaxhighlight>

=={{header|68000 Assembly}}==
When programming in assembly language yourself, generally the addresses of variables are known in advance and chosen by the programmer rather than dynamically determined by the compiler. Therefore you pretty much always know a variable's address at all times.

<syntaxhighlight lang="68000devpac">UserRam equ $100000
Cursor_X equ UserRam ;$100000, byte length
Cursor_Y equ UserRam+1 ;$100001, byte length
SixteenBitData equ UserRam+2 ;$100002, word length (VASM doesn't allow labels to begin with numbers.)
ThirtyTwoBitData equ UserRam+4 ;$100004, long length

;GET THE ADDRESS

LEA ThirtyTwoBitData,A0 ;load $100004 into A0.</syntaxhighlight>

Setting a variable to an address is as simple as storing a desired value in memory. Assembly languages in general do not have automated memory management, so it is important to manage your memory well.

<syntaxhighlight lang="68000devpac">MOVE.L #$11223344,D0
MOVE.L D0,(A0) ; store D0 into ThirtyTwoBitData ($100004)
; HEXDUMP OF $100004:
; $100004: $11
; $100005: $22
; $100006: $33
; $100007: $44</syntaxhighlight>



=={{header|8086 Assembly}}==
When programming in assembly language yourself, generally a variable's address is determined in advance by the programmer. The 8086 differs compared to other machines of its era, where the actual numeric value of the address is not needed to get or set the address of a desired variable. In exchange, a little more work needs to be done to store or retrieve values to/from memory.
{{works with|https://www.dosbox.com DOSBox}}
===Get The Address===
<syntaxhighlight lang="asm">.model small
.stack 1024
.stack 1024
.data
.data
UserRam 256 DUP (0) ;define the next 256 bytes as user RAM, initialize them all to zero.
UserRam 256 DUP (0) ;define the next 256 bytes as user RAM, initialize them all to zero.


myString db "Hello World!,255
.code
.code


Line 37: Line 94:


mov ax, offset UserRam ;load into AX the address of UserRam
mov ax, offset UserRam ;load into AX the address of UserRam
mov di, ax ;load that value into the destination index register</lang>
mov di, ax ;load that value into the destination index register</syntaxhighlight>

The actual numeric value of the address isn't needed, as the label system takes care of that for us. A memory dump routine can show the contents of <code>es:di</code>, displaying the actual memory location.

===Set The Address===
Like with other assembly languages, the terms "variable" and "memory address" are often interchangeable. Setting a variable to an address is just storing a value into memory. After the setup above has taken place, the programmer can store numbers into memory.

<syntaxhighlight lang="asm">mov ax, 0FFFFh
mov [es:di],ax ;store 0xFFFF into the base address of UserRam.</syntaxhighlight>

Alternatively, this would also work:
<syntaxhighlight lang="asm">.model small
.stack 1024
.data
UserRam 256 DUP (0) ;define the next 256 bytes as user RAM, initialize them all to zero.

.code
mov ax, @data ; load the data segment into ax
mov ds,ax ; point the data segment register to the data segment.
; (The 8086 can only load segment registers from ax, bx, cx, dx, or the pop command)


mov ax, 0FFFFh ; load the number 65535 (or -1 if you prefer) into ax.
mov word ptr [ds:UserRam] ; store this quantity in user ram.</syntaxhighlight>



=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AArch64 Raspberry PI 3B */
/* ARM assembly AArch64 Raspberry PI 3B */
/* program adrvar.s */
/* program adrvar.s */
Line 116: Line 197:
ret // retour adresse lr x30
ret // retour adresse lr x30


</syntaxhighlight>
</lang>

=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
BYTE v=[123]

PrintF("Value of variable: %B%E",v)
PrintF("Address of variable: %H%E",@v)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Address_of_a_variable.png Screenshot from Atari 8-bit computer]
<pre>
Value of variable: 123
Address of variable: $249A
</pre>


=={{header|Ada}}==
=={{header|Ada}}==
===Get The Address===
===Get The Address===
<lang ada>The_Address : System.Address;
<syntaxhighlight lang="ada">The_Address : System.Address;
I : Integer;
I : Integer;
The_Address := I'Address;</lang>
The_Address := I'Address;</syntaxhighlight>
===Set The Address===
===Set The Address===
Set the address of a variable to address A100 in hexadecimal
Set the address of a variable to address A100 in hexadecimal
<lang ada>I : Integer;
<syntaxhighlight lang="ada">I : Integer;
for I'Address use 16#A100#;</lang>
for I'Address use 16#A100#;</syntaxhighlight>
Set the address of one variable to the address of another variable, creating an overlay.
Set the address of one variable to the address of another variable, creating an overlay.
<lang ada>I : Integer;
<syntaxhighlight lang="ada">I : Integer;
J : Integer;
J : Integer;
for I'Address use J'Address;</lang>
for I'Address use J'Address;</syntaxhighlight>
{{omit from|Lua}}


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 139: Line 233:
But the value of the actual address is not available
But the value of the actual address is not available
for printing or any arithmetic.
for printing or any arithmetic.
<lang algol68>[4]INT test := (222,444,666,888);
<syntaxhighlight lang="algol68">[4]INT test := (222,444,666,888);
REF INT reference := test[3];
REF INT reference := test[3];
REF INT(reference) := reference + 111;
REF INT(reference) := reference + 111;
print(("test value is now: ",test))</lang>
print(("test value is now: ",test))</syntaxhighlight>
{{out}}
{{out}}
<pre>test value is now: +222 +444 +777 +888</pre>
<pre>test value is now: +222 +444 +777 +888</pre>
Line 156: Line 250:
or to a filestore maintained by the operating system</i>[http://www.xs4all.nl/~jmvdveer/report_5.html#A312aa].
or to a filestore maintained by the operating system</i>[http://www.xs4all.nl/~jmvdveer/report_5.html#A312aa].


To establish a channel with such a device there is a special standard procedure:<lang algol68>PROC establish = (REF FILE file, STRING idf, CHANNEL chan, INT p, l, c) INT: ~</lang>
To establish a channel with such a device there is a special standard procedure:<syntaxhighlight lang="algol68">PROC establish = (REF FILE file, STRING idf, CHANNEL chan, INT p, l, c) INT: ~</syntaxhighlight>
Where the <tt>idf</tt> string is text describing which device to open, and possibly
Where the <tt>idf</tt> string is text describing which device to open, and possibly
options. And <tt>chan</tt> is the actual device type. Standard CHANNELs in
options. And <tt>chan</tt> is the actual device type. Standard CHANNELs in
Line 168: Line 262:
=== Get the address ===
=== Get the address ===
Get the address of the last variable used.
Get the address of the last variable used.
<lang ApplesoftBasic>N = N : PRINT PEEK (131) + PEEK (132) * 256</lang>
<syntaxhighlight lang="applesoftbasic">N = N : PRINT PEEK (131) + PEEK (132) * 256</syntaxhighlight>
Get (find) the address of a function.
Get (find) the address of a function.
<lang ApplesoftBasic>0 DEF FN F(X) = 0
<syntaxhighlight lang="applesoftbasic">0 DEF FN F(X) = 0
1 FOR A = PEEK(105) + PEEK(106) * 256 TO PEEK(107) + PEEK(108) * 256 STEP 7 : IF PEEK(A) <> ASC("F") + 128 OR PEEK(A + 1) <> 0 THEN NEXT A : A = 0 : PRINT "FN F NOT FOUND"
1 FOR A = PEEK(105) + PEEK(106) * 256 TO PEEK(107) + PEEK(108) * 256 STEP 7 : IF PEEK(A) <> ASC("F") + 128 OR PEEK(A + 1) <> 0 THEN NEXT A : A = 0 : PRINT "FN F NOT FOUND"
2 IF A THEN PRINT A
2 IF A THEN PRINT A
</syntaxhighlight>
</lang>


=== Set the address ===
=== Set the address ===
Set the address where variables are stored, but clears all variables.
Set the address where variables are stored, but clears all variables.
<lang ApplesoftBasic>LOMEM: 4096
<syntaxhighlight lang="applesoftbasic">LOMEM: 4096
I% = I% : PRINT PEEK (131) + PEEK (132) * 256
I% = I% : PRINT PEEK (131) + PEEK (132) * 256
</syntaxhighlight>
</lang>
Set the address and length of a string.
Set the address and length of a string.
<lang ApplesoftBasic>S$ = "HELLO" : POKE 768, PEEK (131) : POKE 769, PEEK (132) : A = PEEK(768) + PEEK(769) * 256
<syntaxhighlight lang="applesoftbasic">S$ = "HELLO" : POKE 768, PEEK (131) : POKE 769, PEEK (132) : A = PEEK(768) + PEEK(769) * 256
PRINT S$ : PRINT A "- " PEEK(A) " " PEEK(A + 1) + PEEK(A + 2) * 256
PRINT S$ : PRINT A "- " PEEK(A) " " PEEK(A + 1) + PEEK(A + 2) * 256
POKE 768, ASC("H") : POKE 769, ASC("I") : POKE A, 2: POKE A + 1, 0 : POKE A + 2, 3
POKE 768, ASC("H") : POKE 769, ASC("I") : POKE A, 2: POKE A + 1, 0 : POKE A + 2, 3
PRINT S$ : PRINT A "- " PEEK(A) " " PEEK(A + 1) + PEEK(A + 2) * 256
PRINT S$ : PRINT A "- " PEEK(A) " " PEEK(A + 1) + PEEK(A + 2) * 256
</syntaxhighlight>
</lang>
Set the address of a function.
Set the address of a function.
<lang ApplesoftBasic>0 DEF FN F(X) = 1
<syntaxhighlight lang="applesoftbasic">0 DEF FN F(X) = 1
1 DEF FN B(X) = 2
1 DEF FN B(X) = 2
2 N$ = "F" : GOSUB 8 : FA = A
2 N$ = "F" : GOSUB 8 : FA = A
Line 197: Line 291:
8 FOR A = PEEK(105) + PEEK(106) * 256 TO PEEK(107) + PEEK(108) * 256 STEP 7 : IF PEEK(A) = ASC(LEFT$(N$,1)) + 128 AND PEEK(A + 1) = ASC(MID$(N$ + CHR$(0), 2, 1)) THEN A = A + 2 : RETURN
8 FOR A = PEEK(105) + PEEK(106) * 256 TO PEEK(107) + PEEK(108) * 256 STEP 7 : IF PEEK(A) = ASC(LEFT$(N$,1)) + 128 AND PEEK(A + 1) = ASC(MID$(N$ + CHR$(0), 2, 1)) THEN A = A + 2 : RETURN
9 NEXT A : PRINT "FN " N$ " NOT FOUND"
9 NEXT A : PRINT "FN " N$ " NOT FOUND"
</syntaxhighlight>
</lang>


=={{header|Argile}}==
=={{header|Argile}}==
=== Get the address ===
=== Get the address ===
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<lang Argile>use std, array (: array.arg also defines pointer operators :)
<syntaxhighlight lang="argile">use std, array (: array.arg also defines pointer operators :)
let var = 42
let var = 42
let ptr = &var (: value of ptr is address of var :)
let ptr = &var (: value of ptr is address of var :)
print var (: prints 42 :)
print var (: prints 42 :)
(*ptr)++ (: increments value pointed by ptr :)
(*ptr)++ (: increments value pointed by ptr :)
print var (: prints 43 :)</lang>
print var (: prints 43 :)</syntaxhighlight>
=== Set the address ===
=== Set the address ===
Since we cannot set address of a variable, we use a macro
Since we cannot set address of a variable, we use a macro
that returns a reference.
that returns a reference.
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<lang Argile>use std, array
<syntaxhighlight lang="argile">use std, array
=:mac:= -> int& { * (0x400000 as int*) }
=:mac:= -> int& { * (0x400000 as int*) }
printf "%x\n" mac (: may crash depending on operating system :)
printf "%x\n" mac (: may crash depending on operating system :)
</syntaxhighlight>
</lang>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 290: Line 384:
bx lr /* retour procedure */
bx lr /* retour procedure */
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>x: 2
<syntaxhighlight lang="rebol">x: 2
xInfo: info.get 'x
xInfo: info.get 'x


Line 300: Line 394:
"address of x:" xInfo\address
"address of x:" xInfo\address
"->" from.hex xInfo\address
"->" from.hex xInfo\address
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 307: Line 401:


=={{header|Astro}}==
=={{header|Astro}}==
<lang python>var num = 12
<syntaxhighlight lang="python">var num = 12
var pointer = ptr(num) # get pointer
var pointer = ptr(num) # get pointer


Line 314: Line 408:
@unsafe # bad idea!
@unsafe # bad idea!
pointer.addr = 0xFFFE # set the address
pointer.addr = 0xFFFE # set the address
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Getting or setting the address of a variable is not supported as a builtin function.
Getting or setting the address of a variable is not supported as a builtin function.
However, you can get the address of contents pointed to by the variable structure var
However, you can get the address of contents pointed to by the variable structure var
<lang AutoHotkey>msgbox % &var</lang>
<syntaxhighlight lang="autohotkey">msgbox % &var</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==


Axe supports getting the address of a variable using the degree symbol:
Axe supports getting the address of a variable using the degree symbol:
<lang axe>°A→B
<syntaxhighlight lang="axe">°A→B
.B now contains the address of A</lang>
.B now contains the address of A</syntaxhighlight>


Axe does not support setting the address of a variable directly. However, it does support setting the value of a variable and then dereferencing it:
Axe does not support setting the address of a variable directly. However, it does support setting the value of a variable and then dereferencing it:
<lang axe>1234→A
<syntaxhighlight lang="axe">1234→A
1→{A}</lang>
1→{A}</syntaxhighlight>
This should usually be avoided because TI-OS does not use virtual memory. Writing to arbitrary memory locations can affect the stability of the operating system.
This should usually be avoided because TI-OS does not use virtual memory. Writing to arbitrary memory locations can affect the stability of the operating system.


=={{header|BaCon}}==
=={{header|BaCon}}==


<lang freebasic>
<syntaxhighlight lang="freebasic">
'---get a variable's address
'---get a variable's address
LOCAL x TYPE long
LOCAL x TYPE long
PRINT ADDRESS(x)
PRINT ADDRESS(x)
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
Many BASICs, especially older flavors like [[QuickBASIC]], lack the ability to set a variable's address (and indeed, they pretty much all lack the ability to work with pointers in any fashion).
Many BASICs, especially older flavors like [[QuickBASIC]], lack the ability to set a variable's address (and indeed, they pretty much all lack the ability to work with pointers in any fashion).
<lang qbasic>'get a variable's address:
<syntaxhighlight lang="qbasic">'get a variable's address:
DIM x AS INTEGER, y AS LONG
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
y = VARPTR(x)
Line 349: Line 443:
DIM z AS INTEGER
DIM z AS INTEGER
z = PEEK(y)
z = PEEK(y)
z = z + (PEEK(y) * 256)</lang>
z = z + (PEEK(y) * 256)</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
The original BBC BASIC doesn't provide an address-of operator, but ''BBC BASIC for Windows'' does:
The original BBC BASIC doesn't provide an address-of operator, but ''BBC BASIC for Windows'' does:
<lang bbcbasic>REM get a variable's address:
<syntaxhighlight lang="bbcbasic">REM get a variable's address:
y% = ^x%
y% = ^x%


REM can't set a variable's address, but can access a given memory location (4 bytes):
REM can't set a variable's address, but can access a given memory location (4 bytes):
x% = !y%</lang>
x% = !y%</syntaxhighlight>


With BBC BASIC on other platforms the address of a variable can be found by calling a short piece of machine code, see [http://beebwiki.mdfs.net/Address_of_a_variable BeebWiki].
With BBC BASIC on other platforms the address of a variable can be found by calling a short piece of machine code, see [http://beebwiki.mdfs.net/Address_of_a_variable BeebWiki].

=={{header|Beef}}==
<syntaxhighlight lang="csharp">
int i = 5;
int* p = &i;
</syntaxhighlight>

Set the address:
<syntaxhighlight lang="csharp">
int* p = (int*)((void*)0xDEADBEEF);
</syntaxhighlight>



=={{header|C}} / {{header|C++}}==
=={{header|C}} / {{header|C++}}==
Line 366: Line 472:
=== Get the address ===
=== Get the address ===
Note that <code>void*</code> is a "pure" address which doesn't carry the type information anymore. If you need the type information (e.g. to recover the variable itself in a type safe manner), use a pointer to the appropriate type instead; in this case <code>int*</code>.
Note that <code>void*</code> is a "pure" address which doesn't carry the type information anymore. If you need the type information (e.g. to recover the variable itself in a type safe manner), use a pointer to the appropriate type instead; in this case <code>int*</code>.
<lang cpp>int i;
<syntaxhighlight lang="cpp">int i;
void* address_of_i = &i;</lang>
void* address_of_i = &i;</syntaxhighlight>


'''C++ only:''' C++ allows overloading the <code>&</code> operator. To bypass this, for example in generic code, use the library function <code>addressof</code>:
'''C++ only:''' C++ allows overloading the <code>&</code> operator. To bypass this, for example in generic code, use the library function <code>addressof</code>:


<lang cpp>#include <memory>
<syntaxhighlight lang="cpp">#include <memory>
int i;
int i;
auto address_of_i = std::addressof(i);</lang>
auto address_of_i = std::addressof(i);</syntaxhighlight>


=== Set the address ===
=== Set the address ===
While C++ doesn't directly support putting a variable at a given address, the same effect can be achieved by creating a reference to that address:
While C++ doesn't directly support putting a variable at a given address, the same effect can be achieved by creating a reference to that address:
<lang cpp>int& i = *(int*)0xA100;</lang>
<syntaxhighlight lang="cpp">int& i = *(int*)0xA100;</syntaxhighlight>


If the type of the variable requires initialization, it is necessary to use placement new:
If the type of the variable requires initialization, it is necessary to use placement new:
<lang cpp>#include <new>
<syntaxhighlight lang="cpp">#include <new>
struct S { int i = 0; S() {} };
struct S { int i = 0; S() {} };
auto& s = *new (reinterpret_cast<void*>(0xa100)) S;</lang>
auto& s = *new (reinterpret_cast<void*>(0xa100)) S;</syntaxhighlight>


Overlaying of variables is done with anonymous unions; however at global/namespace scope such variables have to be static (i.e. local to the current file):
Overlaying of variables is done with anonymous unions; however at global/namespace scope such variables have to be static (i.e. local to the current file):
<lang cpp>static union
<syntaxhighlight lang="cpp">static union
{
{
int i;
int i;
int j;
int j;
};</lang>
};</syntaxhighlight>
'''C++ only:''' An alternative (and cleaner) solution is to use references:
'''C++ only:''' An alternative (and cleaner) solution is to use references:
<lang cpp>int i;
<syntaxhighlight lang="cpp">int i;
int& j = i;</lang>
int& j = i;</syntaxhighlight>
Note that in this case, the variables can be non-static.
Note that in this case, the variables can be non-static.


If the type of two overlaid variables is not sufficiently similar, then writes to one may not be reflected in reads from the other, even though they have the same address. This is because the optimizer is free to assume that variables of different types do not alias. To read or write a variable as a different type, use <code>memcpy</code>:
If the type of two overlaid variables is not sufficiently similar, then writes to one may not be reflected in reads from the other, even though they have the same address. This is because the optimizer is free to assume that variables of different types do not alias. To read or write a variable as a different type, use <code>memcpy</code>:


<lang cpp>#include <cstring>
<syntaxhighlight lang="cpp">#include <cstring>
inline float read_as_float(int const& i) { float f; memcpy(&f, &i, sizeof(f)); return f; }
inline float read_as_float(int const& i) { float f; memcpy(&f, &i, sizeof(f)); return f; }
int i = 0x0a112233;
int i = 0x0a112233;
float f = read_as_float(i);</lang>
float f = read_as_float(i);</syntaxhighlight>


{{omit from|Clojure}}


=={{header|C sharp}}==
=={{header|C sharp|C#}}==


Use of pointers in C# is restricted to <code>unsafe</code> sections of code, which is enabled in Microsoft's C# compiler with the commandline parameter <code>/unsafe</code> or in Mono's C# compiler with <code>-unsafe</code> (or <code>--unsafe</code> in older versions).
Use of pointers in C# is restricted to <code>unsafe</code> sections of code, which is enabled in Microsoft's C# compiler with the commandline parameter <code>/unsafe</code> or in Mono's C# compiler with <code>-unsafe</code> (or <code>--unsafe</code> in older versions).
Line 411: Line 516:
Note that void* is a "pure" address which doesn't carry the type information anymore. If you need the type information (e.g. to recover the variable itself in a type safe manner), use a pointer to the appropriate type instead; in this case int*.
Note that void* is a "pure" address which doesn't carry the type information anymore. If you need the type information (e.g. to recover the variable itself in a type safe manner), use a pointer to the appropriate type instead; in this case int*.


<lang csharp>unsafe
<syntaxhighlight lang="csharp">unsafe
{
{
int i = 5;
int i = 5;
void* address_of_i = &i;
void* address_of_i = &i;
}</lang>
}</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 421: Line 526:


===Get Address===
===Get Address===
<syntaxhighlight lang="cobol"> DATA DIVISION.
<lang cobol>data division.
WORKING-STORAGE SECTION.
working-storage section.
01 ptr usage pointer.
01 ptr USAGE POINTER.
01 var pic x(64).
01 var PIC X(64).

PROCEDURE DIVISION.
procedure division.
set ptr to address of var.</lang>
SET ptr TO ADDRESS OF var.</syntaxhighlight>


===Set Address===
===Set Address===
Sets the address of a variable using the <code>BASED</code> clause. There are other methods, in particular <code>LINKAGE SECTION</code> variables.
Sets the address of a variable using the <code>BASED</code> clause. There are other methods, in particular <code>LINKAGE SECTION</code> variables.
<lang cobol>
<syntaxhighlight lang="cobol">
OCOBOL*> Rosetta Code set address example
OCOBOL*> Rosetta Code set address example
*> tectonics: cobc -x setaddr.cob && ./setaddr
*> tectonics: cobc -x setaddr.cob && ./setaddr
program-id. setaddr.
IDENTIFICATION DIVISION.
data division.
PROGRAM-ID. setaddr.
working-storage section.
DATA DIVISION.
01 prealloc pic x(8) value 'somedata'.
WORKING-STORAGE SECTION.
01 var pic x(8) based.
01 prealloc PIC X(8) VALUE 'somedata'.
procedure division.
set address of var to address of prealloc
01 var PIC X(8) BASED.
display var end-display
goback.
PROCEDURE DIVISION.
SET ADDRESS OF var TO ADDRESS OF prealloc
end program setaddr.</lang>
DISPLAY var END-DISPLAY
*> 'somedata'
GOBACK.
END PROGRAM setaddr.
</syntaxhighlight>

=={{header|Commodore BASIC}}==
{{works with|BASIC|7.0 (C-128)}}
The address of a variable in BASIC is readonly, but accessible via the <tt>POINTER</tt> function.

<syntaxhighlight lang="basic">100 REM ALLOCATE ALL VARS FIRST SO THEY DON'T MOVE
110 X=123:Y=456:PX=0:PY=0:I=0:T=0
120 PRINT "BEFORE:X="XCHR$(20)",Y="Y
130 PX=POINTER(X):PY=POINTER(Y)
140 REM VARS ARE STORED IN RAM BANK 1
150 BANK 1
160 FOR I=0 TO 6
170 : T = PEEK(PY+I)
180 : POKE PY+I,PEEK(PX+I)
190 : POKE PX+I,T
200 NEXT I
210 PRINT "AFTER: X="XCHR$(20)",Y="Y</syntaxhighlight>

{{works with|BASIC|2.0 (VIC-20, C-64)}}
With older machines, there's no built-in mechanism in BASIC to find a variable's address, but you can use the internal state of the BASIC interpreter to achieve similar results. Here's a VIC-20/C-64 version that works the same as the above C-128 program:

<syntaxhighlight lang="basic">100 X=PEEK(71)+256*PEEK(72):PX=X:X=123
110 Y=PEEK(71)+256*PEEK(72):PY=Y:Y=456
120 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
130 FOR I=0 TO 6
140 : T = PEEK(PY+I)
150 : POKE PY+I,PEEK(PX+I)
160 : POKE PX+I,T
170 NEXT I
180 PRINT "AFTER: X ="XCHR$(20)", Y ="Y</syntaxhighlight>

They same idea should work on other Commodore computers as well, though at least the address being <tt>PEEK</tt>ed will have to change.
{{Out}}

<pre>BEFORE:X= 123,Y= 456
AFTER: X= 456,Y= 123</pre>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 453: Line 600:
Yet, thanks to Lisp macros and lexical closures, we can create reference values which behave like address of places. A tiny module for doing this is found in <strike>[http://paste.lisp.org/display/71952 Lisppaste #71952]</strike> (now it's available [http://www.kylheku.com/cgit/lisp-snippets/tree/refs.lisp here]), required by the following example:
Yet, thanks to Lisp macros and lexical closures, we can create reference values which behave like address of places. A tiny module for doing this is found in <strike>[http://paste.lisp.org/display/71952 Lisppaste #71952]</strike> (now it's available [http://www.kylheku.com/cgit/lisp-snippets/tree/refs.lisp here]), required by the following example:


<lang lisp>;;; Demonstration of references by swapping two variables using a function rather than a macro
<syntaxhighlight lang="lisp">;;; Demonstration of references by swapping two variables using a function rather than a macro
;;; Needs http://paste.lisp.org/display/71952
;;; Needs http://paste.lisp.org/display/71952
(defun swap (ref-left ref-right)
(defun swap (ref-left ref-right)
Line 468: Line 615:


;; *y* -> 42
;; *y* -> 42
;; *x* -> 0</lang>
;; *x* -> 0</syntaxhighlight>


These references are completely safe to use. There is no way that a place can disappear, leaving a reference dangling, because if a reference is a live object, it prevents the object which contains the referenced place from becoming garbage. Also note that if two references are taken to the same memory location, they are two distinct objects. A function could be provided to test two references for referential equality (do they point to the same object).
These references are completely safe to use. There is no way that a place can disappear, leaving a reference dangling, because if a reference is a live object, it prevents the object which contains the referenced place from becoming garbage. Also note that if two references are taken to the same memory location, they are two distinct objects. A function could be provided to test two references for referential equality (do they point to the same object).
Line 484: Line 631:
We wrap this function with a Lisp foreign call which is properly annotated as returning a C pointer to int. When we call this function, we get an object that behaves like a reference to that location. All we need then is a macro which looks like a storage location.
We wrap this function with a Lisp foreign call which is properly annotated as returning a C pointer to int. When we call this function, we get an object that behaves like a reference to that location. All we need then is a macro which looks like a storage location.


<lang lisp>(use-package :ffi)
<syntaxhighlight lang="lisp">(use-package :ffi)


(defmacro def-libc-call-out (name &rest args)
(defmacro def-libc-call-out (name &rest args)
Line 510: Line 657:
(defsetf get-errno set-errno)
(defsetf get-errno set-errno)


(define-symbol-macro errno (get-errno)))</lang>
(define-symbol-macro errno (get-errno)))</syntaxhighlight>


Test:
Test:
Line 523: Line 670:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE AddressVar;
MODULE AddressVar;
IMPORT SYSTEM,StdLog;
IMPORT SYSTEM,StdLog;
Line 538: Line 685:
x := 10;
x := 10;
END AddressVar.
END AddressVar.
</syntaxhighlight>
</lang>
Execute: ^Q AddressVar.Do<br/>
Execute: ^Q AddressVar.Do<br/>
{{out}}
{{out}}
Line 546: Line 693:


=={{header|Creative Basic}}==
=={{header|Creative Basic}}==
<syntaxhighlight lang="creative basic">
<lang Creative Basic>
== Get ==
== Get ==


Line 619: Line 766:
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem
DELETE pMem
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==


Take the address of a variable:
Take the address of a variable:
<lang d>int i;
<syntaxhighlight lang="d">int i;
int* ip = &i;</lang>
int* ip = &i;</syntaxhighlight>


Using a numeric value:
Using a numeric value:
<lang d>int* ip = cast(int*)0xdeadf00d;</lang>
<syntaxhighlight lang="d">int* ip = cast(int*)0xdeadf00d;</syntaxhighlight>


Locating a "regular" variable at a specific address is not possible.
Locating a "regular" variable at a specific address is not possible.
Line 634: Line 781:
The closest thing is passing a dereferenced pointer to a reference parameter.
The closest thing is passing a dereferenced pointer to a reference parameter.


<lang d>void test(ref int i) {
<syntaxhighlight lang="d">void test(ref int i) {
import std.stdio;
import std.stdio;
writeln(&i);
writeln(&i);
Line 641: Line 788:
void main() {
void main() {
test(* (cast(int*)0xdeadf00d) );
test(* (cast(int*)0xdeadf00d) );
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 648: Line 795:


To get the address of any variable, structure, procedure or function use the <tt>@</tt>-operator:
To get the address of any variable, structure, procedure or function use the <tt>@</tt>-operator:
<lang pascal>var
<syntaxhighlight lang="pascal">var
i: integer;
i: integer;
p: ^integer;
p: ^integer;
Line 654: Line 801:
p := @i;
p := @i;
writeLn(p^);
writeLn(p^);
end;</lang>
end;</syntaxhighlight>
Note, (untyped) constants do not have an address in Pascal.
Note, (untyped) constants do not have an address in Pascal.


A variable can be declared as <tt>absolute</tt> i. e.: to reside at a specific address:
A variable can be declared as <tt>absolute</tt> i. e.: to reside at a specific address:
<lang pascal>var
<syntaxhighlight lang="pascal">var
crtMode: integer absolute $0040;
crtMode: integer absolute $0040;
str: string[100];
str: string[100];
strLen: byte absolute str;
strLen: byte absolute str;
</syntaxhighlight>
</lang>

=={{header|Draco}}==
<syntaxhighlight lang="draco">/* This code uses a CP/M-specific address to demonstrate fixed locations,
* so it will very likely only work under CP/M */
proc nonrec main() void:
/* When declaring a variable, you can let the compiler choose an address */
word var;
/* Or you can set the address manually using @, to a fixed address */
word memtop @ 0x6; /* CP/M stores the top of memory at 0x0006 */
/* or to the address of another variable, by naming that variable */
word var2 @ var; /* var2 will overlap var */
/* This works with both automatically and manually placed variables. */
word memtop2 @ memtop; /* same as "memtop2 @ 0x6" */
/* Once a variable is declared, you can't change its address at runtime. */
var := 1234; /* assign a value to var _and_ var2 */
/* The address of a variable can be retrieved using the & operator.
* However, this returns a pointer type, which is distinct from an
* integer type. To use it as a number, we have to coerce it to an integer
* first. */
writeln("var address=", pretend(&var,word):5, " value=", var:5);
writeln("memtop address=", pretend(&memtop,word):5, " value=", memtop:5);
writeln("var2 address=", pretend(&var2,word):5, " value=", var2:5);
writeln("memtop2 address=", pretend(&memtop2,word):5, " value=", memtop2:5)
corp</syntaxhighlight>
{{out}}
<pre>var address= 276 value= 1234
memtop address= 6 value=58374
var2 address= 276 value= 1234
memtop2 address= 6 value=58374</pre>


=={{header|ERRE}}==
=={{header|ERRE}}==
ERRE hasn't explicit pointers, but only a function that gets the address of a variable
ERRE hasn't explicit pointers, but only a function that gets the address of a variable
<lang>
<syntaxhighlight lang="text">
........
........
A%=100
A%=100
ADDR=VARPTR(A%)
ADDR=VARPTR(A%)
.......
.......
</syntaxhighlight>
</lang>
ADDR contains the value of the address of variable A (from 0 to 65535 because every ERRE module has a 64K address space). ERRE data types is 2 bytes-long for integer, 4 (5 with C-64) for reals and 8 for double-real variables.
ADDR contains the value of the address of variable A (from 0 to 65535 because every ERRE module has a 64K address space). ERRE data types is 2 bytes-long for integer, 4 (5 with C-64) for reals and 8 for double-real variables.
Using this address you can modify the variable's value without using an assignment statement:
Using this address you can modify the variable's value without using an assignment statement:
<lang>
<syntaxhighlight lang="text">
PROGRAM POINTER
PROGRAM POINTER
BEGIN
BEGIN
Line 683: Line 865:
PRINT(A%) ! prints 200
PRINT(A%) ! prints 200
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
Note: With C-64 substitute POKE(ADDR,200) with POKE(ADDR+3,200).
Note: With C-64 substitute POKE(ADDR,200) with POKE(ADDR+3,200).


Line 739: Line 921:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>program test_loc
<syntaxhighlight lang="fortran">program test_loc
implicit none


implicit none
integer :: i
integer :: i
real :: r
real :: r

i = loc (r)
write (*, '(i0)') i


i = loc(r)
end program test_loc</lang>
print *, i
end program</syntaxhighlight>
Note: <code>loc</code> is a common extension that is implemented
Note: <code>loc</code> is a common extension that is implemented
by e.g. the Intel Fortran Compiler, G95 and gfortran.
by e.g. the Intel Fortran Compiler, G95 and gfortran.
Line 754: Line 935:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
One can get the address of a variable using the @ operator:
One can get the address of a variable using the @ operator:
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
Dim a As Integer = 3
Dim a As Integer = 3
Dim p As Integer Ptr = @a
Dim p As Integer Ptr = @a
Print a, p </lang>
Print a, p </syntaxhighlight>
To my knowledge, it is not possible to set the address of a variable to a specific address in FB though (as in C/C++) you can do something like this as a workaround:
To my knowledge, it is not possible to set the address of a variable to a specific address in FB though (as in C/C++) you can do something like this as a workaround:
<lang freebasic>Var p = Cast(Integer Ptr, 1375832)
<syntaxhighlight lang="freebasic">Var p = Cast(Integer Ptr, 1375832)
*p = 42
*p = 42
Print p, *p</lang>
Print p, *p</syntaxhighlight>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>
<syntaxhighlight lang="futurebasic">window 1
include "ConsoleWindow"


dim as short i : i = 575
short i = 575
dim as ptr j : j = NULL
ptr j


j = @i
j = @i


print "Adddress of i ="; j
printf @"Address of i = %ld",j
print "Value of i ="; [j]
print @"Value of i = ";peek word(j)

</lang>
HandleEvents</syntaxhighlight>


Output:
Output:
<pre>
<pre>
Adddress of i = 902164
Adddress of i = 4330713552
Value of i = 575
Value of i = 575
</pre>
</pre>

=={{header|GDScript}}==
{{works with|Godot|4.0}}

GDScript does not expose addresses, however there are reference identifiers (RIDs).

<syntaxhighlight lang="gdscript">
extends MainLoop


func _process(_delta: float) -> bool:
var a := Node.new()
var b := Node.new()

# a and b are different objects with different RIDs
print(a.get_instance_id())
print(b.get_instance_id())

assert(a != b)
assert(a.get_instance_id() != b.get_instance_id())

# Set b to refer to the same object as a
b.free()
b = a

# a and b are now the same object and have the same RID
print(a.get_instance_id())
print(b.get_instance_id())

assert(a == b)
assert(a.get_instance_id() == b.get_instance_id())

a.free()
return true # Exit

</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Line 799: Line 1,016:
The following demonstrates getting the address of a variable and storing/printing it various ways.
The following demonstrates getting the address of a variable and storing/printing it various ways.
It also demonstrates accessing an arbitrary memory location (here the known address of a float) as an integer.
It also demonstrates accessing an arbitrary memory location (here the known address of a float) as an integer.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 830: Line 1,047:
i := (*int32)(unsafe.Pointer(&myVar))
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
fmt.Printf("value as int32: %#08x\n", *i)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
On a 32 bit architecture:
On a 32 bit architecture:
Line 848: Line 1,065:
value as int32: 0x51eb851f</pre>
value as int32: 0x51eb851f</pre>


==IWBASIC==
=={{header|IWBASIC}}==
<syntaxhighlight lang="iwbasic">
<lang IWBASIC>
== Get ==
== Get ==


Line 879: Line 1,096:
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem
DELETE pMem
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
Line 885: Line 1,102:
J hides the details of pointers and memory allocation from the programmer, so it is rarely, if ever, necessary to do this. However, for those times when there is no better substitute, J provides access to these low-level details:
J hides the details of pointers and memory allocation from the programmer, so it is rarely, if ever, necessary to do this. However, for those times when there is no better substitute, J provides access to these low-level details:


<lang> var =: 52 NB. Any variable (including data, functions, operators etc)
<syntaxhighlight lang="text"> var =: 52 NB. Any variable (including data, functions, operators etc)
var_addr =: 15!:6<'var' NB. Get address
var_addr =: 15!:6<'var' NB. Get address
new_var =: 15!:7 var_addr NB. Set address</lang>
new_var =: 15!:7 var_addr NB. Set address</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 899: Line 1,116:
Julia has both mutable and immutable objects. Immutable objects are values, such as constants, bit-based values such as numeric 3, or immutable structs. Immutable objects may not have a single set location in memory, but instead might in some cases be created on demand by the compiled code. Mutable objects such as typical arrays and mutable structs, on the other hand, have addresses on the Julia heap that can be found with specific base Julia functions which use the <code>Ptr</code> type.
Julia has both mutable and immutable objects. Immutable objects are values, such as constants, bit-based values such as numeric 3, or immutable structs. Immutable objects may not have a single set location in memory, but instead might in some cases be created on demand by the compiled code. Mutable objects such as typical arrays and mutable structs, on the other hand, have addresses on the Julia heap that can be found with specific base Julia functions which use the <code>Ptr</code> type.


To get the memory address of a Julia object, one can use <code>pointer_from_objref(object)</code>, and the reverse is accomplished by <code>unsafe_pointer_to_objref(ptr)</code>: <lang julia>julia> x = [1, 2, 3]
To get the memory address of a Julia object, one can use <code>pointer_from_objref(object)</code>, and the reverse is accomplished by <code>unsafe_pointer_to_objref(ptr)</code>: <syntaxhighlight lang="julia">julia> x = [1, 2, 3]
julia> ptr = pointer_from_objref(x)
julia> ptr = pointer_from_objref(x)
Ptr{Void} @0x000000010282e4a0
Ptr{Void} @0x000000010282e4a0
Line 906: Line 1,123:
1
1
2
2
3</lang> The latter is "unsafe" because it only works if <code>ptr</code> refers to a valid heap-allocated "boxed" Julia object, which can only be safely allocated by Julia itself.
3</syntaxhighlight> The latter is "unsafe" because it only works if <code>ptr</code> refers to a valid heap-allocated "boxed" Julia object, which can only be safely allocated by Julia itself.


<p>Another common use of pointers is for arrays of values, which are typically passed in low-level C-like libraries via pointers to contiguous sets of values in memory. This is accomplished in Julia by the <code>pointer(A)</code> function, which returns a pointer to the data stored in a high-level Julia array <code>A</code>. Given a pointer <code>p</code> to values of a given type, the <code>i</code>-th value (numbered starting at 1 for the value pointed to by <code>p</code>) can be read or written by the low-level <code>unsafe_load(p, i)</code> and <code>unsafe_store!(p, val, i)</code> functions, or it can be converted back to a high-level Julia array type by the <code>pointer_to_array(p, dimensions)</code> function:<lang julia>julia> A = [1, 2.3, 4]
<p>Another common use of pointers is for arrays of values, which are typically passed in low-level C-like libraries via pointers to contiguous sets of values in memory. This is accomplished in Julia by the <code>pointer(A)</code> function, which returns a pointer to the data stored in a high-level Julia array <code>A</code>. Given a pointer <code>p</code> to values of a given type, the <code>i</code>-th value (numbered starting at 1 for the value pointed to by <code>p</code>) can be read or written by the low-level <code>unsafe_load(p, i)</code> and <code>unsafe_store!(p, val, i)</code> functions, or it can be converted back to a high-level Julia array type by the <code>pointer_to_array(p, dimensions)</code> function:<syntaxhighlight lang="julia">julia> A = [1, 2.3, 4]
3-element Array{Float64,1}:
3-element Array{Float64,1}:
1.0
1.0
Line 931: Line 1,148:
1.0
1.0
2.3
2.3
3.14149</lang>
3.14149</syntaxhighlight>


Finally, an arbitrary integer can be converted to a pointer type with <code>convert</code>, which allows an arbitrary address to be converted into and viewed as an array of an arbitrary type and read or written (although this can easily result in a crash if an invalid address is used). In the following example, we create a "new" length-two array <code>B</code> at an address offset by 8 bytes from the address of the data in <code>A</code> above, which will make it point to the second element of <code>A</code>:<lang julia>julia>
Finally, an arbitrary integer can be converted to a pointer type with <code>convert</code>, which allows an arbitrary address to be converted into and viewed as an array of an arbitrary type and read or written (although this can easily result in a crash if an invalid address is used). In the following example, we create a "new" length-two array <code>B</code> at an address offset by 8 bytes from the address of the data in <code>A</code> above, which will make it point to the second element of <code>A</code>:<syntaxhighlight lang="julia">julia>
julia> q = convert(Ptr{Float64}, 0x0000000113f70d68)
julia> q = convert(Ptr{Float64}, 0x0000000113f70d68)
Ptr{Float64} @0x0000000113f70d68
Ptr{Float64} @0x0000000113f70d68
Line 940: Line 1,157:
2-element Array{Float64,1}:
2-element Array{Float64,1}:
2.3
2.3
3.14149</lang>
3.14149</syntaxhighlight>


{{omit from|K}}


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 949: Line 1,165:
However, Kotlin/Native which is currently (January 2018) available as a pre-release version does support pointers to enable it to interoperate with C code. The following program shows how to obtain the address of a variable which has been allocated on the native heap. It does not appear to be possible to allocate a variable at a particular address.
However, Kotlin/Native which is currently (January 2018) available as a pre-release version does support pointers to enable it to interoperate with C code. The following program shows how to obtain the address of a variable which has been allocated on the native heap. It does not appear to be possible to allocate a variable at a particular address.
{{works with|Ubuntu|14.04}}
{{works with|Ubuntu|14.04}}
<lang scala>// Kotlin Native v0.5
<syntaxhighlight lang="scala">// Kotlin Native v0.5


import kotlinx.cinterop.*
import kotlinx.cinterop.*
Line 958: Line 1,174:
with(intVar) { println("Value is $value, address is $rawPtr") }
with(intVar) { println("Value is $value, address is $rawPtr") }
nativeHeap.free(intVar)
nativeHeap.free(intVar)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 970: Line 1,186:
Users are not supposed to access these addresses. During the post-processing phase the addresses which have not been "consumed" by the evaluation are automatically evaluated to show the related values in a convenient way. For instance:
Users are not supposed to access these addresses. During the post-processing phase the addresses which have not been "consumed" by the evaluation are automatically evaluated to show the related values in a convenient way. For instance:


<syntaxhighlight lang="scheme">
<lang Scheme>


1) lambdas
1) lambdas
Line 995: Line 1,211:
-> _QUOT_124 // as replaced and protected before post-processing
-> _QUOT_124 // as replaced and protected before post-processing
-> {+ 1 2} // as displayed after post-processing
-> {+ 1 2} // as displayed after post-processing
</syntaxhighlight>
</lang>

=={{header|Lua}}==
Pure/native Lua does not support true pointer operations. Memory management is automatic, and garbage-collected, so at best you can hold a temporary reference to the allocated memory. However the "virtual address" of complex types is discoverable (and is in fact how the internals deal with assignment, equality testing, etc), and userdata types typically reveal an actual physical address.
<syntaxhighlight lang="lua">t = {}
print(t)
f = function() end
print(f)
c = coroutine.create(function() end)
print(c)
u = io.open("/dev/null","w")
print(u)
print(_G, _ENV) -- global/local environments (are same here)
print(string.format("%p %p %p", print, string, string.format)) -- themselves formatted as pointers</syntaxhighlight>
{{out}}
<pre>table: 00000000001d93b0
function: 00000000001dcb30
thread: 00000000001de088
file (00007ffe2612fa90)
table: 00000000001d1e80 table: 00000000001d1e80
0000000065b9cd60 00000000001d90b0 0000000065ba34f0</pre>


=={{header|Maple}}==
=={{header|Maple}}==


To obtain the address of any expression in Maple, use the builtin function <code>addressof</code>.
To obtain the address of any expression in Maple, use the builtin function <code>addressof</code>.
<lang Maple>> addressof( x );
<syntaxhighlight lang="maple">> addressof( x );
18446884674469911422</lang>The inverse operation is <code>pointto</code>:<lang Maple>
18446884674469911422</syntaxhighlight>The inverse operation is <code>pointto</code>:<syntaxhighlight lang="maple">
> pointto( 18446884674469911422 );
> pointto( 18446884674469911422 );
x</lang>This works for any expression, not just variables:<lang Maple>> addressof( sin( x )^2 + cos( x )^2 );
x</syntaxhighlight>This works for any expression, not just variables:<syntaxhighlight lang="maple">> addressof( sin( x )^2 + cos( x )^2 );
18446884674469972158
18446884674469972158


> pointto( 18446884674469972158 );
> pointto( 18446884674469972158 );
2 2
2 2
sin(x) + cos(x)</lang>
sin(x) + cos(x)</syntaxhighlight>

=={{header|M2000 Interpreter}}==
From version 12, VarPtr() can return address for variables and array items.

We can't set an address to a variable. We can link a variable name with an existing variable. Is the same as passing by reference.

<syntaxhighlight lang="m2000 interpreter">
module checkVarptr {
declare GetMem8 lib "msvbvm60.GetMem8" {Long addr, Long retValue}
long long x=1234567812345678&&, z
dim k(2,2,2) as long long
call GetMem8(VarPtr(x), VarPtr(z))
call GetMem8(VarPtr(x), VarPtr(k(1,0,1)))
print z=x
print k(1,0,1)=x
link z to m
print VarPtr(z)=VarPtr(m)
checkref(&z)
sub checkref(&p)
print VarPtr(z)=VarPtr(p)
end sub
}
checkVarptr
module checkVarptr {
// Using byref at GemMem8 signature
declare GetMem8 lib "msvbvm60.GetMem8" {long &addr, long &retValue}
declare PutMem8 lib "msvbvm60.PutMem8" {long &addr, retValue as long long}
long long x=1234567812345678&&, z
dim k(2,2,2) as long long
call GetMem8(&x, &z)
call GetMem8(&x, &k(1,0,1))
print z=x
print k(1,0,1)=x
checkref(&z)
print z=987654321987654321&&
sub checkref(&p)
print VarPtr(z)=VarPtr(p)
call PutMem8(&p, 987654321987654321&&)
end sub
}
checkVarptr
</syntaxhighlight>
{{out}}
<pre>
True
True
True
True
</pre>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
===Get Address===
===Get Address===
<lang modula2>MODULE GetAddress;
<syntaxhighlight lang="modula2">MODULE GetAddress;


FROM SYSTEM IMPORT ADR;
FROM SYSTEM IMPORT ADR;
Line 1,023: Line 1,308:
WriteInt(adr, 0);
WriteInt(adr, 0);
WriteLn;
WriteLn;
END GetAddress.</lang>
END GetAddress.</syntaxhighlight>


===Set Address===
===Set Address===
<lang modula2>MODULE SetAddress;
<syntaxhighlight lang="modula2">MODULE SetAddress;


CONST adress = 134664460;
CONST adress = 134664460;
Line 1,034: Line 1,319:
BEGIN
BEGIN
(*do nothing*)
(*do nothing*)
END SetAddress.</lang>
END SetAddress.</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
===Get Address===
===Get Address===
<lang nanoquery>import native
<syntaxhighlight lang="nanoquery">import native


a = 5
a = 5


println format("0x%08x", native.address(a))</lang>
println format("0x%08x", native.address(a))</syntaxhighlight>
{{out}}
{{out}}
<pre>0xc46be580</pre>
<pre>0xc46be580</pre>
Line 1,048: Line 1,333:
===Set Address===
===Set Address===
We cannot directly modify the address of a variable that has already be created, but we can create a pointer and move it to point at a different address.
We cannot directly modify the address of a variable that has already be created, but we can create a pointer and move it to point at a different address.
<lang nanoquery>import native
<syntaxhighlight lang="nanoquery">import native


a = 123
a = 123
Line 1,057: Line 1,342:


ptr = native.address(b)
ptr = native.address(b)
println native.object(ptr)</lang>
println native.object(ptr)</syntaxhighlight>
{{out}}
{{out}}
<pre>123
<pre>123
Line 1,064: Line 1,349:
=={{header|NewLISP}}==
=={{header|NewLISP}}==
===Get Address===
===Get Address===
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(set 'a '(1 2 3))
(set 'a '(1 2 3))
(address a)
(address a)
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>var x = 12
<syntaxhighlight lang="nim">var x = 12
var xptr = addr(x) # Get address of variable
var xptr = addr(x) # Get address of variable
echo cast[int](xptr) # and print it
echo cast[int](xptr) # and print it
xptr = cast[ptr int](0xFFFE) # Set the address</lang>
xptr = cast[ptr int](0xFFFE) # Set the address</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
===Get Address===
===Get Address===
<syntaxhighlight lang="oberon2">
<pre>
VAR a: LONGINT;
VAR a: LONGINT;
VAR b: INTEGER;
VAR b: INTEGER;
Line 1,083: Line 1,368:
b := 10;
b := 10;
a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)
a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)
</syntaxhighlight>
</pre>


===Set Address===
===Set Address===
<syntaxhighlight lang="oberon2">
<pre>
SYSTEM.PUT(a, b); (* Sets the address of b to the address of a *)
SYSTEM.PUT(a, b); (* Sets the address of b to the address of a *)
</syntaxhighlight>
</pre>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,100: Line 1,385:
To get the address, we re-interpret the boxed value as an integer; however, this will get the address divided by 2, since the integer only uses the upper 31 (or 63) bits. Therefore, we need to shift this number left by one to get the real address. However, <code>int</code> cannot hold all the bits of the address, so if we shift we will lose a bit, so we use the <code>nativeint</code> type to represent it instead:
To get the address, we re-interpret the boxed value as an integer; however, this will get the address divided by 2, since the integer only uses the upper 31 (or 63) bits. Therefore, we need to shift this number left by one to get the real address. However, <code>int</code> cannot hold all the bits of the address, so if we shift we will lose a bit, so we use the <code>nativeint</code> type to represent it instead:


<lang ocaml>let address_of (x:'a) : nativeint =
<syntaxhighlight lang="ocaml">let address_of (x:'a) : nativeint =
if Obj.is_block (Obj.repr x) then
if Obj.is_block (Obj.repr x) then
Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *)
Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *)
Line 1,112: Line 1,397:
Printf.printf "%nx\n" (address_of b);;
Printf.printf "%nx\n" (address_of b);;
let c = 17 in
let c = 17 in
Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *)</lang>
Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *)</syntaxhighlight>

=={{header|Odin}}==

<syntaxhighlight lang="odin">package main

main :: proc() {
i : int = 42
ip : ^int = &i // Get address of variable

address := uintptr(0xdeadf00d)
ip2 := cast(^int)address // Set the address
}</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,122: Line 1,419:
For instance, here, after creating and setting a variable A, we store the corresponding word into a variable B :
For instance, here, after creating and setting a variable A, we store the corresponding word into a variable B :


<lang Oforth>tvar: A
<syntaxhighlight lang="oforth">tvar: A
10 to A
10 to A


Line 1,135: Line 1,432:
[1] (Integer) 12
[1] (Integer) 12
[2] (Variable) #A
[2] (Variable) #A
>ok</lang>
>ok</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Line 1,163: Line 1,460:


=={{header|Panoramic}}==
=={{header|Panoramic}}==
<syntaxhighlight lang="panoramic">
<lang Panoramic>
== Get ==
== Get ==


Line 1,207: Line 1,504:
''Note:'' An attempt to poke a real or an integer (Panoramic's only numeric types) value of less than 0 or of more than
''Note:'' An attempt to poke a real or an integer (Panoramic's only numeric types) value of less than 0 or of more than
255 will cause an error.
255 will cause an error.
</syntaxhighlight>
</lang>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
In GP you can sent the address to built-in commands like issquare
In GP you can sent the address to built-in commands like issquare
<lang parigp>issquare(n, &m)</lang>
<syntaxhighlight lang="parigp">issquare(n, &m)</syntaxhighlight>
but you cannot directly compute with it. You can view the address of a variable and other debugging information with the
but you cannot directly compute with it. You can view the address of a variable and other debugging information with the
<pre>\x</pre>
<pre>\x</pre>
Line 1,223: Line 1,520:
=={{header|Perl}}==
=={{header|Perl}}==
To get the address, get the reference to a variable, and either stringify it, or use Scalar::Util's refaddr() to get just the address. Also see Devel::Peek.
To get the address, get the reference to a variable, and either stringify it, or use Scalar::Util's refaddr() to get just the address. Also see Devel::Peek.
<lang perl>use Scalar::Util qw(refaddr);
<syntaxhighlight lang="perl">use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; # 140502490125712</lang>
print refaddr(\my $v), "\n"; # 140502490125712</syntaxhighlight>
Alternatively, the address (in hexadecimal) can be directly obtained with <code>printf</code>:
Alternatively, the address (in hexadecimal) can be directly obtained with <code>printf</code>:
<lang perl>printf "%p", $v; # 7fc949039590</lang>
<syntaxhighlight lang="perl">printf "%p", $v; # 7fc949039590</syntaxhighlight>
Use Devel::Pointer::PP if you want to dereference a certain address in memory.
Use Devel::Pointer::PP if you want to dereference a certain address in memory.


Line 1,232: Line 1,529:


Simple reference (address) manipulation.
Simple reference (address) manipulation.
<lang perl>my $a = 12;
<syntaxhighlight lang="perl">my $a = 12;
my $b = \$a; # get reference
my $b = \$a; # get reference
$$b = $$b + 30; # access referenced value
$$b = $$b + 30; # access referenced value
print $a; # prints 42</lang>
print $a; # prints 42</syntaxhighlight>


Example how to make variable overlay.
Example how to make variable overlay.
<lang perl>my $a = 12;
<syntaxhighlight lang="perl">my $a = 12;
our $b; # you can overlay only global variables (this line is only for strictness)
our $b; # you can overlay only global variables (this line is only for strictness)
*b = \$a;
*b = \$a;
print $b; # prints 12
print $b; # prints 12
$b++;
$b++;
print $a; # prints 13</lang>
print $a; # prints 13</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Line 1,259: Line 1,556:
compiler only omits the appropriate binary for the currently selected target architecture.
compiler only omits the appropriate binary for the currently selected target architecture.
You can also use allocate/free with peek/poke to obtain similar effects.
You can also use allocate/free with peek/poke to obtain similar effects.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">address</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">address</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">V</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">V</span>
Line 1,284: Line 1,581:
<span style="color: #000000;">address</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">address</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,298: Line 1,595:
it is a negative number, and for cons pairs a positive number. The same function
it is a negative number, and for cons pairs a positive number. The same function
'adr' can then be used to convert that pointer back to the original object.
'adr' can then be used to convert that pointer back to the original object.
<lang PicoLisp>: (setq X 7)
<syntaxhighlight lang="picolisp">: (setq X 7)
-> 7
-> 7


Line 1,311: Line 1,608:


: X
: X
-> (a b c)</lang>
-> (a b c)</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==


<syntaxhighlight lang="pl/i">
<lang PL/I>
declare addr builtin; /* retrieve address of a variable */
declare addr builtin; /* retrieve address of a variable */
declare ptradd builtin; /* pointer addition */
declare ptradd builtin; /* pointer addition */
Line 1,349: Line 1,646:
end;
end;
end;
end;
</syntaxhighlight>
</lang>

=={{header|PL/M}}==
<syntaxhighlight lang="pli">100H:
/* THERE IS NO STANDARD LIBRARY
THIS DEFINES SOME BASIC I/O USING CP/M */
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PUT$CHAR: PROCEDURE (C); DECLARE C BYTE; CALL BDOS(2,C); END PUT$CHAR;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
NEWLINE: PROCEDURE; CALL PRINT(.(13,10,'$')); END NEWLINE;

/* PRINT 16-BIT HEX VALUE (POINTER) */
PRINT$HEX: PROCEDURE (N);
DECLARE N ADDRESS, (I, C) BYTE;
DO I=0 TO 3;
IF I <> 3 THEN C = SHR(N,12-4*I) AND 0FH;
ELSE C = N AND 0FH;
IF C >= 10 THEN C = C - 10 + 'A';
ELSE C = C + '0';
CALL PUT$CHAR(C);
END;
END PRINT$HEX;

/* OF COURSE WE WILL NEED SOME VALUES TO POINT AT TOO */
DECLARE FOO ADDRESS INITIAL (0F00H);
DECLARE BAR ADDRESS INITIAL (0BA1H);

/* OK, NOW ON TO THE DEMONSTRATION */

/* THE ADDRESS OF A VARIABLE CAN BE RETRIEVED BY PREPENDING IT WITH A
DOT, E.G.: */
CALL PRINT(.'FOO IS $'); CALL PRINT$HEX(FOO);
CALL PRINT(.' AND ITS ADDRESS IS $'); CALL PRINT$HEX(.FOO);
CALL NEWLINE;

CALL PRINT(.'BAR IS $'); CALL PRINT$HEX(BAR);
CALL PRINT(.' AND ITS ADDRESS IS $'); CALL PRINT$HEX(.BAR);
CALL NEWLINE;

/* PL/M DOES NOT HAVE C-STYLE POINTERS. INSTEAD IT HAS 'BASED' VARIABLES.
WHEN A VARIABLE IS DECLARED 'BASED', ITS ADDRESS IS STORED IN ANOTHER
VARIABLE.
NOTE HOWEVER THAT THE 'ADDRESS' DATATYPE IS SIMPLY A 16-BIT INTEGER,
AND DOES NOT INTRINSICALLY POINT TO ANYTHING.
THE FOLLOWING DECLARES A VARIABLE 'POINTER', WHICH WILL HOLD AN ADDRESS,
AND A VARIABLE 'VALUE' WHICH WILL BE LOCATED AT WHATEVER THE VALUE IN
'POINTER' IS. */
DECLARE POINTER ADDRESS;
DECLARE VALUE BASED POINTER ADDRESS;

/* WE CAN NOW ACCESS 'FOO' AND 'BAR' THROUGH 'VALUE' BY ASSIGNING THEIR
ADDRESSES TO 'POINTER'. */
POINTER = .FOO;
CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER);
CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;
POINTER = .BAR;
CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER);
CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;

/* MUTATION IS ALSO POSSIBLE OF COURSE */
VALUE = 0BA3H;
CALL PRINT(.'VALUE IS NOW $'); CALL PRINT$HEX(VALUE);
CALL PRINT(.' AND BAR IS NOW $'); CALL PRINT$HEX(BAR); CALL NEWLINE;

/* LASTLY, PL/M SUPPORTS ANONYMOUS CONSTANTS.
YOU CAN TAKE THE ADDRESS OF AN IMMEDIATE CONSTANT, AND PL/M
WILL STORE THE CONSTANT IN THE CONSTANT POOL AND GIVE YOU ITS
ADDRESS. THE CONSTANT MUST HOWEVER BE A BYTE OR A LIST OF BYTES. */
POINTER = .(0FEH,0CAH); /* NOTE THE DOT, AND THE LOW-ENDIAN 16-BIT VALUE */
CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER);
CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;

/* NOTE THAT THIS IS ALSO HOW STRINGS WORK - SEE ALL THE DOTS IN FRONT
OF THE STRINGS IN THE 'PRINT' CALLS */
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>FOO IS 0F00 AND ITS ADDRESS IS 03FA
BAR IS 0BA1 AND ITS ADDRESS IS 03FC
POINTER IS 03FA AND VALUE IS 0F00
POINTER IS 03FC AND VALUE IS 0BA1
VALUE IS NOW 0BA3 AND BAR IS NOW 0BA3
POINTER IS 034D AND VALUE IS CAFE</pre>

=={{header|Plain English}}==
To get the address of a variable, use:
<syntaxhighlight lang="text">[a variable]'s whereabouts</syntaxhighlight>
Note that this address cannot be modified.


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
<lang powerbasic>'get a variable's address:
<syntaxhighlight lang="powerbasic">'get a variable's address:
DIM x AS INTEGER, y AS LONG
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
y = VARPTR(x)
Line 1,369: Line 1,759:
'*can* set the address of an array
'*can* set the address of an array
DIM zzz(1) AS BYTE AT y
DIM zzz(1) AS BYTE AT y
'zzz(0) = low byte of x, zzz(1) = high byte of x</lang>
'zzz(0) = low byte of x, zzz(1) = high byte of x</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Get the address of a variable using the '@' operator.
Get the address of a variable using the '@' operator.
<lang PureBasic>a.i = 5
<syntaxhighlight lang="purebasic">a.i = 5
MessageRequester("Address",Str(@a))</lang>
MessageRequester("Address",Str(@a))</syntaxhighlight>




Set the address of a structured pointer. The pointer can be dereferenced to interact with it's data. Ensure that there is access to the memory address that is assigned to the pointer (i.e. part of allocated memory).
Set the address of a structured pointer. The pointer can be dereferenced to interact with it's data. Ensure that there is access to the memory address that is assigned to the pointer (i.e. part of allocated memory).
<lang PureBasic>a.i = 5
<syntaxhighlight lang="purebasic">a.i = 5
*b.Integer = @a ;set *b equal to the address of variable a
*b.Integer = @a ;set *b equal to the address of variable a
*c.Integer = $A100 ;set *c to point at memory location $A100 (in hex)
*c.Integer = $A100 ;set *c to point at memory location $A100 (in hex)
Line 1,384: Line 1,774:


MessageRequester("Address",Str(*b)) ;display the address being pointed at by *b
MessageRequester("Address",Str(*b)) ;display the address being pointed at by *b
MessageRequester("Value",Str(*b\i)) ;de-reference the pointer *b to display the data being pointed at</lang>
MessageRequester("Value",Str(*b\i)) ;de-reference the pointer *b to display the data being pointed at</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 1,392: Line 1,782:
The Python ''id()'' function returns a unique ID for any object. This just happens to be implemented as the base address of the object in C Python[http://docs.python.org/library/functions.html#id]; but that is not guaranteed by the semantics of the language and should not be considered a standard, nor used as such. But for comparison purposes the ID can be used as an address, since different extant objects will have different IDs.
The Python ''id()'' function returns a unique ID for any object. This just happens to be implemented as the base address of the object in C Python[http://docs.python.org/library/functions.html#id]; but that is not guaranteed by the semantics of the language and should not be considered a standard, nor used as such. But for comparison purposes the ID can be used as an address, since different extant objects will have different IDs.


<lang python>foo = object() # Create (instantiate) an empty object
<syntaxhighlight lang="python">foo = object() # Create (instantiate) an empty object
address = id(foo)</lang>
address = id(foo)</syntaxhighlight>


In addition some folks have written binary Python modules which implement "peek" and "poke" operations, but these are non-standard.
In addition some folks have written binary Python modules which implement "peek" and "poke" operations, but these are non-standard.

=={{header|Quackery}}==

Quackery does not have variables, and its memory model is based on dynamic arrays ("nests" in Quackery parlance) rather than a single continuous block of RAM, so, for example, an entry on the return stack has two parts; a pointer to a nest and a numerical offset into the nest (i.e. the location of an item within the nest) If the offset is non-negative, the offset is from the (zero-based) start of the nest, and if the offset is negative it is from the end of the nest, with the last item in the nest being at position -1.

The word <code>peek</code> returns a item located within a nest, given a nest and an offset.

The word <code>poke</code> takes a Quackery object, a nest, and an offset as arguments and returns a new nest, similar to the argument nest, except with the contents of the offset location replaced by the specified object. (Nests are immutable except under specific circumstances.)

Illustrating this as a dialogue in the shell (the Quackery REPL.)

<pre>/O> [ 10 11 12 13 14 ] is mynest ( create a named nest containing numbers )
... ' mynest 2 peek echo ( print the content of item #2 in mynest )
...
12
Stack empty.

/O> 99999 ' mynest 2 poke echo ( replace 12 with 99999 and print result )
...
[ 10 11 99999 13 14 ]
Stack empty.</pre>

<code>quid</code> returns a numerical value associated with an object in Quackery. See the discussion of <code>id()</code> in the [[Address of a variable#Python|Python entry]]. Quackery is implemented in Python, and <code>quid</code> in Quackery is equivalent to <code>id()</code> in Python.

=={{header|QB64}}==

<syntaxhighlight lang="qb64">
' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions
Type points
x As Integer
y As Integer
z As Integer
End Type

Dim Shared m(3) As _MEM
Dim Shared Saved As points, first As points

m(1) = _Mem(first.x)
m(2) = _Mem(first.y)
m(3) = _Mem(first.z)

print "QB64 way to manage address of variable..."
first.x = 3: first.y = 5: first.z = 8
Print first.x, first.y, first.z
Save first
first.x = 30: first.y = 50: first.z = 80
Print first.x, first.y, first.z

RestoreIt
Print first.x, first.y, first.z

_MemFree m(1)
_MemFree m(2)
_MemFree m(3)
End

Sub Save (F As points)
Saved.x = F.x
Saved.y = F.y
Saved.z = F.z
End Sub

Sub RestoreIt
_MemPut m(1), m(1).OFFSET, Saved.x
_MemPut m(2), m(2).OFFSET, Saved.y
_MemPut m(3), m(3).OFFSET, Saved.z
End Sub
</syntaxhighlight>

<syntaxhighlight lang="qb64">
' Full demonstration of being together Qbasic and QB64 methods for accessing and modifying memory directly
Dim A As Integer, B As String, C(1 To 4) As Double

Print " OLD FASHION MODE OF QBASIC / QUICKBASIC"
Sleep 2: Cls
'Print
Print " GETTING ADDRESS OF VARIABLE"
Print "address of variable QuickBasic compatible in 16 bit OS is emulated in QB64"
Print "Qbasic and QuickBasic used as address a Segment and an Offset"
Print "and by cause many QBasic statements change addresses of variables "
Print "for reorganization of RAM it is higly reccomanded to use"
Print "immediately the address of variable got by Varptr and Varseg"
Print "address of A "; VarSeg(A); "-"; VarPtr(A)
Print "address of the first byte of string B "; VarSeg(B); "-"; VarPtr(B)
Print "address of the 2nd element of array C"; VarSeg(C(2)); "-"; VarPtr(C(2))
Print "address of string B from actual data Segment"; SAdd(B)
Print
Print "Direct access to ram video example "
Print " setting Text video ram as Segment": Def Seg = &HB800
Print "reading at offset 240 of text video ram "; Peek(240)
Print "changing at offset 240 of text video ram with"; Asc("@"); " from e to @"
Poke 240, Asc("@")
Print "changing foreground and background color of a character in text video ram "
Poke 241, Peek(241) Xor &B110111
Poke 265, Peek(265) Xor &B010101
Poke 267, Peek(267) Xor &B001010
Def Seg
Print
Print " CREATING VARIABLE AT A SPECIFIC ADDRESS"
Print " created variable D as single at "; VarSeg(d); "-"; VarPtr(d)
Print "Using the variable in normal way"
Print d
d = 100
Print d
Print " press any key to continue..."; Input$(1)
Cls
Print "Only QB64 methods... _MEM functions"
Dim M As _MEM

A = 2: Print "A is "; A
M = _Mem(A) ' it accesses to variable A

_MemPut M, M.OFFSET, 10 As INTEGER ' it modifies value of A
Print " and now A is "; A

Print "d is "; d
d = _MemGet(M, M.OFFSET, Integer) ' it gets value of A into d
Print "and now d is "; d
_MemFree M
End
</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Line 1,401: Line 1,912:
===With the library pryr===
===With the library pryr===


<lang rsplus>
<syntaxhighlight lang="rsplus">
x <- 5
x <- 5
y <- x
y <- x
Line 1,411: Line 1,922:
pryr::address(x)
pryr::address(x)
pryr::address(y)
pryr::address(y)
</syntaxhighlight>
</lang>


===Without any libraries===
===Without any libraries===
<lang rsplus>
<syntaxhighlight lang="rsplus">
address <- function(obj) {
address <- function(obj) {
paste0("0x", substring(sub(" .*$","",capture.output(.Internal(inspect(obj)))),2))
paste0("0x", substring(sub(" .*$","",capture.output(.Internal(inspect(obj)))),2))
Line 1,427: Line 1,938:
address(x)
address(x)
address(y)
address(y)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,438: Line 1,949:


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(require ffi/unsafe)
(require ffi/unsafe)


(define (madness v) ; i'm so sorry
(define (madness v) ; i'm so sorry
(cast v _racket _gcpointer))</lang>
(cast v _racket _gcpointer))</syntaxhighlight>


To test that it is doing "sane" things, you can retrieve the value of the C short located at the pointer produced. Racket objects start with a 2-byte tag indicating their type. These calls should all produce fairly small numbers: the Racket source I'm looking at uses only the first 259 tag values. Small fixnums are stored directly in tagged pointers, so attempting this dereferencing on the pointer madness gives you from a fixnum will most likely segfault your process.
To test that it is doing "sane" things, you can retrieve the value of the C short located at the pointer produced. Racket objects start with a 2-byte tag indicating their type. These calls should all produce fairly small numbers: the Racket source I'm looking at uses only the first 259 tag values. Small fixnums are stored directly in tagged pointers, so attempting this dereferencing on the pointer madness gives you from a fixnum will most likely segfault your process.


<lang racket>
<syntaxhighlight lang="racket">
(ptr-ref (madness +) _short)
(ptr-ref (madness +) _short)
(ptr-ref (madness (/ 4 3)) _short)
(ptr-ref (madness (/ 4 3)) _short)
Line 1,454: Line 1,965:
(ptr-ref (madness #\a) _short)
(ptr-ref (madness #\a) _short)
(ptr-ref (madness 'foo) _short)
(ptr-ref (madness 'foo) _short)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)

{{works with|Rakudo|2015.12}}
<lang perl6>my $x;
<syntaxhighlight lang="raku" line>my $x;
say $x.WHERE;
say $x.WHERE;


Line 1,468: Line 1,979:
$x = 42;
$x = 42;
say $y; # 42
say $y; # 42
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>7857931379550584425</pre>
<pre>7857931379550584425</pre>
How you set the address of a variable (or any other object) is outside the purview of the Perl 6 language, but Perl 6 supports pluggable object representations, and any given representation scheme could conceivably allow an existing address to be treated as an object candidate where that makes sense. Memory-mapped structs are not unreasonable and are likely to be supported on VMs that allow it.
How you set the address of a variable (or any other object) is outside the purview of Raku, but the language supports pluggable object representations, and any given representation scheme could conceivably allow an existing address to be treated as an object candidate where that makes sense. Memory-mapped structs are not unreasonable and are likely to be supported on VMs that allow it.


=={{header|RapidQ}}==
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim TheAddress as long
Dim TheAddress as long
Dim SecVar as byte
Dim SecVar as byte
Line 1,494: Line 2,005:
'SecVar is now also = 102
'SecVar is now also = 102
showmessage "SecVar = " + str$(SecVar)
showmessage "SecVar = " + str$(SecVar)
</syntaxhighlight>
</lang>


=={{header|Retro}}==
=={{header|Retro}}==
Line 1,500: Line 2,011:


===Get The Address===
===Get The Address===
<lang Retro>'a var
<syntaxhighlight lang="retro">'a var
&a</lang>
&a</syntaxhighlight>


===Set The Address===
===Set The Address===
Create variable '''b''' and point it to address '''100'''
Create variable '''b''' and point it to address '''100'''
<lang Retro>'b var
<syntaxhighlight lang="retro">'b var
#100 @Dictionary d:xt store</lang>
#100 @Dictionary d:xt store</syntaxhighlight>


===Byte Addressing===
===Byte Addressing===
Line 1,514: Line 2,025:
To read the value at byte address 100:
To read the value at byte address 100:


<lang Retro>'example/ByteAddressing.forth include
<syntaxhighlight lang="retro">'example/ByteAddressing.forth include
#100 b:fetch</lang>
#100 b:fetch</syntaxhighlight>


Or to alter the value at byte address 100:
Or to alter the value at byte address 100:


<lang Retro>$e #100 b:store</lang>
<syntaxhighlight lang="retro">$e #100 b:store</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,527: Line 2,038:
<br>the state of any variable (defined or not defined, its value, length of the variable's value).
<br>the state of any variable (defined or not defined, its value, length of the variable's value).
<br><br>It is possible to use the BIF (shown below)&nbsp; (at least, in the original REXX)
<br><br>It is possible to use the BIF (shown below)&nbsp; (at least, in the original REXX)
<lang rexx>zzz = storage(xxx)</lang>
<syntaxhighlight lang="rexx">zzz = storage(xxx)</syntaxhighlight>
(but only in '''some''' REXX interpreters) &nbsp; to access the internal REXX pool of variables, but it
(but only in '''some''' REXX interpreters) &nbsp; to access the internal REXX pool of variables, but it
<br>would depend on the (internal) REXX internal structure(s) and almost likely be not portable nor
<br>would depend on the (internal) REXX internal structure(s) and almost likely be not portable nor
Line 1,544: Line 2,055:
For classes that do not override the <code>to_s</code> method, the <code>to_s</code> method also shows the address.
For classes that do not override the <code>to_s</code> method, the <code>to_s</code> method also shows the address.


<lang ruby>>foo = Object.new # => #<Object:0x10ae32000>
<syntaxhighlight lang="ruby">>foo = Object.new # => #<Object:0x10ae32000>
>id = foo.object_id # => 2238812160
>id = foo.object_id # => 2238812160
>"%x" % (id << 1) # => "10ae32000"
>"%x" % (id << 1) # => "10ae32000"
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==
Line 1,553: Line 2,064:
It is not possible to change the memory address of an existing variable in Rust directly. However, you could make a copy of the value and then write it to a specific address.
It is not possible to change the memory address of an existing variable in Rust directly. However, you could make a copy of the value and then write it to a specific address.


<lang rust>let v1 = vec![vec![1,2,3]; 10];
<syntaxhighlight lang="rust">let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
println!("Original address: {:p}", &v1);
let mut v2;
let mut v2;
Line 1,563: Line 2,074:
// scope, which is good since then we'd have a vector of free'd vectors
// scope, which is good since then we'd have a vector of free'd vectors
unsafe {ptr::write(addr, v1)}
unsafe {ptr::write(addr, v1)}
println!("New address: {:p}", &v2);</lang>
println!("New address: {:p}", &v2);</syntaxhighlight>


Get the memory address of a variable:
Get the memory address of a variable:
<lang rust>let var = 1;
<syntaxhighlight lang="rust">let var = 1;
println!("address of var: {:p}", &var);</lang>
println!("address of var: {:p}", &var);</syntaxhighlight>


Get the value at a certain memory address:
Get the value at a certain memory address:
<lang rust>let address: usize = 0x7ffc8f303130;
<syntaxhighlight lang="rust">let address: usize = 0x7ffc8f303130;
unsafe {
unsafe {
let val = *(address as *const usize);
let val = *(address as *const usize);
println!("value at {}: {:?}", address, val);
println!("value at {}: {:?}", address, val);
}</lang>
}</syntaxhighlight>


Set the value at a certain memory address:
Set the value at a certain memory address:
<lang rust>unsafe {
<syntaxhighlight lang="rust">unsafe {
*(0x7ffc8f303130 as *mut usize) = 1;
*(0x7ffc8f303130 as *mut usize) = 1;
// Note that this invokes undefined behavior if 0x7ffc8f303130 is uninitialized. In that case, std::ptr::write should be used.
// Note that this invokes undefined behavior if 0x7ffc8f303130 is uninitialized. In that case, std::ptr::write should be used.
std::ptr::write(0x7ffc8f303130 as *mut usize, 1);
std::ptr::write(0x7ffc8f303130 as *mut usize, 1);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
Line 1,587: Line 2,098:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var n = 42;
<syntaxhighlight lang="ruby">var n = 42;
say Sys.refaddr(\n); # prints the address of the variable
say Sys.refaddr(\n); # prints the address of the variable
say Sys.refaddr(n); # prints the address of the object at which the variable points to</lang>
say Sys.refaddr(n); # prints the address of the object at which the variable points to</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,602: Line 2,113:
You asked for it, and here it is:
You asked for it, and here it is:
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>|p|
<syntaxhighlight lang="smalltalk">|p|
p := Point x:10 y:20.
p := Point x:10 y:20.
ObjectMemory addressOf:p.
ObjectMemory addressOf:p.
ObjectMemory collectGarbage.
ObjectMemory collectGarbage.
ObjectMemory addressOf:p "may return another value"</lang>
ObjectMemory addressOf:p "may return another value"</syntaxhighlight>
to deal with non-Smalltalk objects, all Smalltalks provide libraries to pass-in and out parameters to foreign function calls (FFI). The underlying memory block will not be moved by the garbage collector and the address can be passed to external (eg. C, C++, asm) functions.
to deal with non-Smalltalk objects, all Smalltalks provide libraries to pass-in and out parameters to foreign function calls (FFI). The underlying memory block will not be moved by the garbage collector and the address can be passed to external (eg. C, C++, asm) functions.
For those, we can allocate a block of memory and fiddle around with its "address":
For those, we can allocate a block of memory and fiddle around with its "address":
{{works with|Smalltalk/X}}{{works with|VisualWorks Smalltalk}}
{{works with|Smalltalk/X}}{{works with|VisualWorks Smalltalk}}
<lang smalltalk>|ptr|
<syntaxhighlight lang="smalltalk">|ptr|
ptr := ExternalBytes new:10.
ptr := ExternalBytes new:10.
ptr address.
ptr address.
ptr byteAt:1 put: 16rFF.</lang>
ptr byteAt:1 put: 16rFF.</syntaxhighlight>


However, there are "reference holders", similar to box-objects in scheme/lisp. In Smalltalk these are called "ValueHolder" and are heavily used in UI frameworks. Usually, they are used with the observer pattern as shown in the following example:
However, there are "reference holders", similar to box-objects in scheme/lisp. In Smalltalk these are called "ValueHolder" and are heavily used in UI frameworks. Usually, they are used with the observer pattern as shown in the following example:
<lang>|holder|
<syntaxhighlight lang="text">|holder|
holder := ValueHolder with:123.
holder := ValueHolder with:123.
holder onChangeSend:#someChange to:someone.
holder onChangeSend:#someChange to:someone.
holder value: 234
holder value: 234
</syntaxhighlight>
</lang>


{{omit from|Smart BASIC}}


=={{header|Stata}}==
=={{header|Stata}}==
Line 1,628: Line 2,138:
It's not possible to set the address of a variable, but on can get the address of a variable or a function with the & operator.
It's not possible to set the address of a variable, but on can get the address of a variable or a function with the & operator.


<lang stata>a = 1
<syntaxhighlight lang="stata">a = 1
&a
&a


Line 1,635: Line 2,145:
}
}


&f()</lang>
&f()</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>
<syntaxhighlight lang="swift">
class MyClass { }
class MyClass { }


Line 1,668: Line 2,178:


test()
test()
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,688: Line 2,198:
<br>
<br>
{{libheader|critcl}}
{{libheader|critcl}}
<lang tcl>package require critcl
<syntaxhighlight lang="tcl">package require critcl
# This code assumes an ILP32 architecture, like classic x86 or VAX.
# This code assumes an ILP32 architecture, like classic x86 or VAX.
critcl::cproc peek {int addr} int {
critcl::cproc peek {int addr} int {
Line 1,708: Line 2,218:
*u.a = value;
*u.a = value;
}
}
package provide poker 1.0</lang>
package provide poker 1.0</syntaxhighlight>
Demonstrating:
Demonstrating:
<lang tcl>package require poker
<syntaxhighlight lang="tcl">package require poker


# Increment a memory location; this will probably crash if you try for real.
# Increment a memory location; this will probably crash if you try for real.
Line 1,716: Line 2,226:
# for embedded programming...
# for embedded programming...
set where 0x12340
set where 0x12340
poke $where [expr {[peek $where] + 1}]</lang>
poke $where [expr {[peek $where] + 1}]</syntaxhighlight>
Have great care with this sort of code; the damage you can do by writing to random locations is considerable and being able to read from anywhere could allow information to flow to otherwise unauthorized programs.
Have great care with this sort of code; the damage you can do by writing to random locations is considerable and being able to read from anywhere could allow information to flow to otherwise unauthorized programs.


Line 1,734: Line 2,244:
foo .
foo .


{{omit from|TorqueScript}}


=={{header|VBA}}==
=={{header|VBA}}==
The '''VarPtr''' function allows one to get the address of a variable. There are also functions to peek/poke values at a given address.
The '''VarPtr''' function allows one to get the address of a variable. There are also functions to peek/poke values at a given address.


<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
Declare Sub GetMem1 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Byte)
Declare Sub GetMem1 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Byte)
Declare Sub GetMem2 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Integer)
Declare Sub GetMem2 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Integer)
Line 1,762: Line 2,271:
Call PutMem4(ptr, 87654321)
Call PutMem4(ptr, 87654321)
Debug.Print a
Debug.Print a
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 1,781: Line 2,290:


Dim ptrX As New IntPtr(&HA100)
Dim ptrX As New IntPtr(&HA100)

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn main() {
var := 42
address_of_var := &var // pointer to variable
println(&address_of_var) // reference
println(*address_of_var) // dereference a reference // 42
}
</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>addr.x
<syntaxhighlight lang="wart">addr.x
=> 27975840</lang>
=> 27975840</syntaxhighlight>


<code>addr</code> is guaranteed to provide a stable identifier ''for this session''. The address is just a number like any other and you can perform all the arithmetic you like on it. However, there's no way to dereference an address back into a value, so this is not pointer arithmetic. The primary use of <code>addr</code> is to check if two objects are the same and not just copies, like Common Lisp's <code>eq</code> operator.
<code>addr</code> is guaranteed to provide a stable identifier ''for this session''. The address is just a number like any other and you can perform all the arithmetic you like on it. However, there's no way to dereference an address back into a value, so this is not pointer arithmetic. The primary use of <code>addr</code> is to check if two objects are the same and not just copies, like Common Lisp's <code>eq</code> operator.


<lang wart>if (addr.x = addr.y)
<syntaxhighlight lang="wart">if (addr.x = addr.y)
..</lang>
..</syntaxhighlight>


As a result, Wart has only one way to compare values: by default two objects are considered equal if they are structurally isomorphic. (You can override it if you want a different behavior.)
As a result, Wart has only one way to compare values: by default two objects are considered equal if they are structurally isomorphic. (You can override it if you want a different behavior.)
Line 1,799: Line 2,318:


You can, of course, assign a variable of one reference type to another which under the hood copies the pointer so that both variables access the same data store.
You can, of course, assign a variable of one reference type to another which under the hood copies the pointer so that both variables access the same data store.
<lang ecmascript>var a = [1, 2, 3, 4]
<syntaxhighlight lang="wren">var a = [1, 2, 3, 4]
var b = a // now 'a' and 'b' both point to the same List data
var b = a // now 'a' and 'b' both point to the same List data
b[3] = 5
b[3] = 5
Line 1,805: Line 2,324:
System.print("'a' is %(a)") // the previous change is of course reflected in 'a' as well
System.print("'a' is %(a)") // the previous change is of course reflected in 'a' as well
var t = Object.same(a, b) // tells you whether 'a' and 'b' refer to the same object in memory
var t = Object.same(a, b) // tells you whether 'a' and 'b' refer to the same object in memory
System.print("'a' and 'b' are the same object? %(t ? "yes" : "no")")</lang>
System.print("'a' and 'b' are the same object? %(t ? "yes" : "no")")</syntaxhighlight>


{{out}}
{{out}}
Line 1,816: Line 2,335:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
For SVR4 Unix-like style assembler the address of a variable is its symbol. (On some systems the names of C language variables have an extra leading underscore.)
For SVR4 Unix-like style assembler the address of a variable is its symbol. (On some systems the names of C language variables have an extra leading underscore.)
<lang Assembler> movl my_variable, %eax</lang>
<syntaxhighlight lang="assembler"> movl my_variable, %eax</syntaxhighlight>


For SVR4 style code destined for a shared library it's necessary to fetch the address from the global offset table to ensure position independent code. That table is found relative to the program counter using the special <code>_GLOBAL_OFFSET_TABLE_</code> (or on some systems extra leading underscore <code>__GLOBAL_OFFSET_TABLE_</code>). The C compiler normally does this in <code>%ebx</code> but for hand-crafted assembler anything equivalent is possible.
For SVR4 style code destined for a shared library it's necessary to fetch the address from the global offset table to ensure position independent code. That table is found relative to the program counter using the special <code>_GLOBAL_OFFSET_TABLE_</code> (or on some systems extra leading underscore <code>__GLOBAL_OFFSET_TABLE_</code>). The C compiler normally does this in <code>%ebx</code> but for hand-crafted assembler anything equivalent is possible.


<lang Assembler> call eip_to_eax
<syntaxhighlight lang="assembler"> call eip_to_eax
addl $_GLOBAL_OFFSET_TABLE_, %eax
addl $_GLOBAL_OFFSET_TABLE_, %eax
movl my_variable@GOT(%eax), %eax
movl my_variable@GOT(%eax), %eax
Line 1,826: Line 2,345:
eip_to_eax:
eip_to_eax:
movl (%esp), %eax
movl (%esp), %eax
ret</lang>
ret</syntaxhighlight>


=={{header|XLISP}}==
=={{header|XLISP}}==
To get the address in the heap of a variable <code>X</code>, use:
To get the address in the heap of a variable <code>X</code>, use:
<lang lisp>(%ADDRESS-OF X)</lang>
<syntaxhighlight lang="lisp">(%ADDRESS-OF X)</syntaxhighlight>
If by "setting the address" we mean compelling the system to store a variable at a particular address of our choosing, then there is no easy way to do that.
If by "setting the address" we mean compelling the system to store a variable at a particular address of our choosing, then there is no easy way to do that.


Line 1,844: Line 2,363:
instead of a 32-bit relative address, when used on a 'real' variable.
instead of a 32-bit relative address, when used on a 'real' variable.


<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int A, B;
int A, B;
[B:= addr A;
[B:= addr A;
Line 1,850: Line 2,369:
B(0):= $1234ABCD;
B(0):= $1234ABCD;
HexOut(0, A); CrLf(0);
HexOut(0, A); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,874: Line 2,393:
5</pre>
5</pre>


=={{header|Z80 Assembly}}==
A variable's address is known in advance if the programmer is writing the assembly code themselves. In order to load from a variable, the address must be specified as an operand. So "getting the address" doesn't really apply to Z80 Assembly.

Setting an address is just storing a register into memory. There are several ways to do this:
===Specifying a Memory Location===
Only the accumulator <code>A</code> can do this. If you want to store another 8-bit register's contents directly into memory, you'll need to load that register's contents into <code>A</code> first:
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
ld (foo),a ;store A into memory location &C000
ld a,b ;copy B to A
ld (bar),a ;store "B" into memory location &C001</syntaxhighlight>

===Using BC or DE===
Only the accumulator <code>A</code> can do this. If you want to store another 8-bit register's contents into the address pointed to by BC or DE, you'll need to load that register's contents into <code>A</code> first:
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001

ld bc,foo ;notice the lack of parentheses here. This is important.
ld (bc),a

ld de,bar
ld (de),a</syntaxhighlight>

===Using HL===
The 8-bit registers <code>A,B,C,D,E</code> can all do this. H and L cannot, unless the value being stored happens to equal that "half" of the memory location.
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
ld hl,foo
ld (hl),b ;store the contents of B into foo

;since bar just happens to equal foo+1, we can do this:

inc hl
ld (hl),c ;store the contents of C into bar</syntaxhighlight>

===16-Bit Values into A Specified Memory Location===
Storing a 16-Bit value is a little more complicated. The registers <code>BC,DE,HL,IX,IY,SP</code> can all do this, with a specified memory location. The "low byte" of the register (<code>C, E, L, IXL, IYL,</code> and the low byte of <code>SP</code>) are stored at the memory location specified in parentheses, and the "high byte" of the register (<code>B, D, H, IXH, IYH,</code> and the high byte of <code>SP</code>) are stored in the memory location <i>after that</i>. The Game Boy/Sharp LR35902 can only do this with SP, and no other registers.

<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001

ld (foo),bc ;store C into "foo" and B into "bar"</syntaxhighlight>

Beware! In this example, the second instruction clobbers part of the first. It's important to be careful when storing 16-bit values into memory.
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001

ld (foo),de ;store E into &C000 and D into &C001
ld (bar),bc ;store C into &C001 and B into &C002</syntaxhighlight>

=={{header|Zig}}==
{{works with|Zig|0.11.0}}
<syntaxhighlight lang="zig">const std = @import("std");

pub fn main() !void {
const stdout = std.io.getStdOut().writer();
var i: i32 = undefined;
var address_of_i: *i32 = &i;

try stdout.print("{x}\n", .{@intFromPtr(address_of_i)});
}</syntaxhighlight>

{{Omit From|MATLAB}}
{{Omit From|Metafont}}
{{Omit From|MUMPS|The interpreter handles the addressing}}
{{Omit From|NSIS}}
{{omit from|8th|Impossible to access address of a variable}}
{{omit from|8th|Impossible to access address of a variable}}
{{omit from|AWK}}
{{omit from|AWK}}
{{omit from|bc|Impossible to access address of a variable}}
{{omit from|bc|Impossible to access address of a variable}}
{{omit from|Brlcad}}
{{omit from|Brlcad}}
{{omit from|Clojure}}
{{omit from|Commodore BASIC}}
{{omit from|Commodore BASIC}}
{{omit from|dc|Impossible to access address of a variable}}
{{omit from|dc|Impossible to access address of a variable}}
{{omit from|Déjà Vu}}
{{omit from|Déjà Vu}}
{{omit from|E}}
{{omit from|Eiffel}}
{{omit from|Eiffel}}
{{omit from|Erlang}}
{{omit from|Erlang}}
{{omit from|E}}
{{omit from|Factor}}
{{omit from|Factor}}
{{omit from|Falcon|Falcon does not support direct access of variable pointers}}
{{omit from|Falcon|Falcon does not support direct access of variable pointers}}
Line 1,890: Line 2,477:
{{omit from|GUISS}}
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Haskell}}
{{omit from|Icon}}
{{omit from|JavaScript}}
{{omit from|JavaScript}}
{{omit from|Joy}}
{{omit from|Joy}}
{{omit from|Icon}}{{omit from|Unicon}}
{{omit from|K}}
{{omit from|LaTeX}}
{{omit from|LaTeX}}
{{omit from|Lily}}
{{omit from|Lilypond}}
{{omit from|Lilypond}}
{{omit from|Lily}}
{{omit from|Logtalk}}
{{omit from|Logtalk}}
{{omit from|M4}}
{{omit from|M4}}
{{omit from|Make}}
{{omit from|Make}}
{{Omit From|MATLAB}}
{{omit from|Mathematica}}
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|Maxima}}
{{Omit From|Metafont}}
{{omit from|ML/I}}
{{omit from|ML/I}}
{{Omit From|MUMPS|The interpreter handles the addressing}}
{{omit from|NetRexx}}
{{omit from|NetRexx}}
{{Omit From|NSIS}}
{{omit from|OCaml}}
{{omit from|OCaml}}
{{omit from|Octave}}
{{omit from|Octave}}
{{omit from|Openscad}}
{{omit from|Openscad}}
{{omit from|Oz}}
{{omit from|Oz}}
{{omit from|PHP}}
{{omit from|PlainTeX}}
{{omit from|PlainTeX}}
{{omit from|PHP}}
{{omit from|Scratch}}
{{omit from|Scratch}}
{{omit from|Smart BASIC}}
{{omit from|TI-89 BASIC}}
{{omit from|TI-89 BASIC}}
{{omit from|TorqueScript}}
{{omit from|TPP}}
{{omit from|TPP}}
{{omit from|Unicon}}
{{omit from|UNIX Shell}}
{{omit from|Unlambda|Does not have variables.}}
{{omit from|Unlambda|Does not have variables.}}
{{omit from|Verilog}}
{{omit from|Verilog}}
{{omit from|VHDL}}
{{omit from|VHDL}}
{{omit from|XSLT}}
{{omit from|XSLT}}
{{omit from|UNIX Shell}}
{{omit from|zkl}}
{{omit from|zkl}}

Latest revision as of 09:32, 6 November 2023

Task
Address of a variable
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses


Task

Demonstrate how to get the address of a variable and how to set the address of a variable.

360 Assembly

Get the Address

To get the address of a variable, use LA (load address) instead of L (load):

         LA    R3,I                load address of I
...
I        DS    F

Set the Address

To set a variable dynamically at the same address of an other variable, use a DSECT (dummy section):

         USING MYDSECT,R12 
         LA    R12,I               set @J=@I
         L     R2,J                now J is at the same location as I
...
I        DS    F
MYDSECT  DSECT 
J        DS    F

6502 Assembly

When programming in assembly language yourself, generally the addresses of variables are known in advance and chosen by the programmer rather than dynamically determined by the compiler. Loading values from RAM into memory requires the programmer to specify the address as the operand. This is true for zero-page memory, absolute memory addresses, and memory-mapped ports whose location is defined by the hardware manufacturer. Typically, the assembly programmer will use labels to ease this process, which get converted to memory addresses automatically when the program is assembled.

;;;;;;; zero page RAM memory addresses
CursorX equ $00
CursorY equ $01
temp    equ $02
;;;;;;; memory-mapped hardware registers
BorderColor equ $D020

Joystick1   equ $DC01
Joystick2   equ $DC00

Rather than setting the address of a variable, in assembly the programmer stores a calculated quantity in an address. The terms "memory address" and "variable" are often used interchangably.

LDA #$20 ; load a constant into the accumulator

CLC
ADC #$50
ASL 
SBC #$30 ; do some math

STA temp ; store the result in a temp variable (really a zero-page memory address).

6502 assemblers treat a number without a # in front as a memory address.

LDA #$30 ;load into the accumulator the constant value 0x30
LDA $30  ;load into the accumulator the value stored at memory address 0x0030.

The only exception to this rule is when defining bytes. These do not have # in front, but are treated as constants nonetheless:

byte $30,$20,$10,$00 ;these are constant numeric values, not memory addresses.

68000 Assembly

When programming in assembly language yourself, generally the addresses of variables are known in advance and chosen by the programmer rather than dynamically determined by the compiler. Therefore you pretty much always know a variable's address at all times.

UserRam equ $100000
Cursor_X equ UserRam           ;$100000, byte length
Cursor_Y equ UserRam+1         ;$100001, byte length
SixteenBitData equ UserRam+2   ;$100002, word length (VASM doesn't allow labels to begin with numbers.)
ThirtyTwoBitData equ UserRam+4 ;$100004, long length 

;GET THE ADDRESS

LEA ThirtyTwoBitData,A0        ;load $100004 into A0.

Setting a variable to an address is as simple as storing a desired value in memory. Assembly languages in general do not have automated memory management, so it is important to manage your memory well.

MOVE.L #$11223344,D0
MOVE.L D0,(A0) ; store D0 into ThirtyTwoBitData ($100004)
; HEXDUMP OF $100004:
; $100004: $11
; $100005: $22
; $100006: $33
; $100007: $44


8086 Assembly

When programming in assembly language yourself, generally a variable's address is determined in advance by the programmer. The 8086 differs compared to other machines of its era, where the actual numeric value of the address is not needed to get or set the address of a desired variable. In exchange, a little more work needs to be done to store or retrieve values to/from memory.

Works with: [DOSBox]

Get The Address

.model small
.stack 1024
.data
UserRam 256 DUP (0) ;define the next 256 bytes as user RAM, initialize them all to zero.

.code

mov ax, seg UserRam         ;load into AX the segment where UserRam is stored.
mov es, ax                  ;load that value into the Extra Segment register

mov ax, offset UserRam      ;load into AX the address of UserRam
mov di, ax                  ;load that value into the destination index register

The actual numeric value of the address isn't needed, as the label system takes care of that for us. A memory dump routine can show the contents of es:di, displaying the actual memory location.

Set The Address

Like with other assembly languages, the terms "variable" and "memory address" are often interchangeable. Setting a variable to an address is just storing a value into memory. After the setup above has taken place, the programmer can store numbers into memory.

mov ax, 0FFFFh
mov [es:di],ax      ;store 0xFFFF into the base address of UserRam.

Alternatively, this would also work:

.model small
.stack 1024
.data
UserRam 256 DUP (0)            ;define the next 256 bytes as user RAM, initialize them all to zero.

.code
mov ax, @data                  ; load the data segment into ax
mov ds,ax                      ; point the data segment register to the data segment. 
                               ; (The 8086 can only load segment registers from ax, bx, cx, dx, or the pop command)


mov ax, 0FFFFh                 ; load the number 65535 (or -1 if you prefer) into ax.
mov word ptr [ds:UserRam]      ; store this quantity in user ram.


AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AArch64 Raspberry PI 3B */
/*  program adrvar.s   */
/*************************************/
/* Constantes                        */
/*************************************/
.equ STDOUT, 1
.equ WRITE,  64
.equ EXIT,   93
/*************************************/
/* Initialized data                  */
/*************************************/
.data
szMessage:      .asciz "Hello. \n"       // message
szRetourLigne:  .asciz "\n"
qValDeb:        .quad 5                   // value 5 in array of 8 bytes
/*************************************/
/* No Initialized data               */
/*************************************/
.bss
qValeur:  .skip  8                       // reserve 8 bytes in memory
/*************************************/
/* Program code                      */
/*************************************/
.text
.global main 
main:
    ldr x0,=szMessage                    // adresse of message short program
    bl affichageMess                     // call function
                                         //  or
    ldr x0,qAdrszMessage                 // adresse of message big program (size code > 4K)
    bl affichageMess                     // call function

    ldr x1,=qValDeb                      // adresse of variable -> x1  short program
    ldr x0,[x1]                          // value of iValdeb  -> x0
    ldr x1,qAdriValDeb                   // adresse of variable -> x1  big program
    ldr x0,[x1]                          // value of iValdeb  -> x0

    /* set variables  */
    ldr x1,=qValeur                      // adresse of variable -> x1  short program
    str x0,[x1]                          // value of x0 ->  iValeur
    ldr x1,qAdriValeur                   // adresse of variable -> x1  big program
    str x0,[x1]                          // value of x0 ->  iValeur
 
 
 /* end of  program */
    mov x0,0                             // return code
    mov x8,EXIT                          // request to exit program
    svc 0                                // perform the system call
qAdriValDeb:            .quad qValDeb
qAdriValeur:            .quad qValeur
qAdrszMessage:          .quad szMessage
qAdrszRetourLigne:      .quad szRetourLigne
/******************************************************************/
/*     String display with  size compute                          */ 
/******************************************************************/
/* x0 contains string address (string ended with zero binary) */
affichageMess:
    stp x0,x1,[sp,-16]!        // save  registers
    stp x2,x8,[sp,-16]!        // save  registers
    mov x2,0                   // size counter
1:                             // loop start
    ldrb w1,[x0,x2]            // load a byte
    cbz w1,2f                  // if zero -> end string
    add x2,x2,#1               // else increment counter
    b 1b                       // and loop
2:                             // x2 =  string size
    mov x1,x0                  // string address
    mov x0,STDOUT              // output Linux standard
    mov x8,WRITE               // code call system "write"
    svc 0                      // call systeme Linux
    ldp x2,x8,[sp],16          // restaur  2 registres
    ldp x0,x1,[sp],16          // restaur  2 registres
    ret                        // retour adresse lr x30

Action!

PROC Main()
  BYTE v=[123]

  PrintF("Value of variable: %B%E",v)
  PrintF("Address of variable: %H%E",@v)
RETURN
Output:

Screenshot from Atari 8-bit computer

Value of variable: 123
Address of variable: $249A

Ada

Get The Address

The_Address : System.Address;
I : Integer;
The_Address := I'Address;

Set The Address

Set the address of a variable to address A100 in hexadecimal

I : Integer;
for I'Address use 16#A100#;

Set the address of one variable to the address of another variable, creating an overlay.

I : Integer;
J : Integer;
for I'Address use J'Address;

ALGOL 68

Basically ALGOL 68 refuses to let the programmer access the memory directly. The language does allow "references" any variables. These references are effectively the address a particular variable. But the value of the actual address is not available for printing or any arithmetic.

[4]INT test := (222,444,666,888);
REF INT reference := test[3];
REF INT(reference) := reference + 111;
print(("test value is now: ",test))
Output:
test value is now:        +222       +444       +777       +888

The other reason specific addresses are using in languages like C to manipulate devices. For this purpose site are expected to implement channels for their programmers to use. To quote the ALGOL 68 Revised Report: A "channel" corresponds to one or more physical devices (e.g., a card reader, a card punch or a line printer, or even to a set up in nuclear physics the results of which are collected by the computer), or to a filestore maintained by the operating system[1].

To establish a channel with such a device there is a special standard procedure:

PROC establish = (REF FILE file, STRING idf, CHANNEL chan, INT p, l, c) INT: ~

Where the idf string is text describing which device to open, and possibly options. And chan is the actual device type. Standard CHANNELs in ALGOL 68 are stand in channel, stand out channel, and stand back channel. These determine the type of the pre opened stdio FILEs stand in, stand out, and stand back. A site would be expected to implement their own CHANNELs for network connections, database queries and particle accelerators etc.

Applesoft BASIC

Get the address

Get the address of the last variable used.

N = N : PRINT PEEK (131) + PEEK (132) * 256

Get (find) the address of a function.

0 DEF FN F(X) = 0
1 FOR A = PEEK(105) + PEEK(106) * 256 TO PEEK(107) + PEEK(108) * 256 STEP 7 : IF PEEK(A) <> ASC("F") + 128 OR PEEK(A + 1) <> 0 THEN NEXT A : A = 0 : PRINT "FN F NOT FOUND"
2 IF A THEN PRINT A

Set the address

Set the address where variables are stored, but clears all variables.

LOMEM: 4096
I% = I% : PRINT PEEK (131) + PEEK (132) * 256

Set the address and length of a string.

S$ = "HELLO" : POKE 768, PEEK (131) : POKE 769, PEEK (132) : A = PEEK(768) + PEEK(769) * 256
PRINT S$ : PRINT A "- " PEEK(A) " " PEEK(A + 1) + PEEK(A + 2) * 256
POKE 768, ASC("H") : POKE 769, ASC("I") : POKE A, 2: POKE A + 1, 0 : POKE A + 2, 3
PRINT S$ : PRINT A "- " PEEK(A) " " PEEK(A + 1) + PEEK(A + 2) * 256

Set the address of a function.

0 DEF FN F(X) = 1
1 DEF FN B(X) = 2
2 N$ = "F" : GOSUB 8 : FA = A
3 N$ = "B" : GOSUB 8 : BA = A
4 PRINT FN F(0)
5 POKE FA, PEEK(BA) : POKE FA + 1, PEEK(BA + 1)
6 PRINT FN F(0)
7 END
8 FOR A = PEEK(105) + PEEK(106) * 256 TO PEEK(107) + PEEK(108) * 256 STEP 7 : IF PEEK(A) = ASC(LEFT$(N$,1)) + 128 AND PEEK(A + 1) = ASC(MID$(N$ + CHR$(0), 2, 1)) THEN A = A + 2 : RETURN
9 NEXT A : PRINT "FN " N$ " NOT FOUND"

Argile

Get the address

Works with: Argile version 1.0.0
use std, array		(: array.arg also defines pointer operators :)
let var = 42
let ptr = &var		(: value of ptr is address of var :)
print var		(: prints 42 :)
(*ptr)++		(: increments value pointed by ptr :)
print var		(: prints 43 :)

Set the address

Since we cannot set address of a variable, we use a macro that returns a reference.

Works with: Argile version 1.0.0
use std, array
=:mac:= -> int& { * (0x400000 as int*) }
printf "%x\n" mac	(: may crash depending on operating system :)

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program adrvar.s   */

/* Constantes    */
.equ STDOUT, 1
.equ WRITE,  4
.equ EXIT,   1
/* Initialized data */
.data
szMessage:      .asciz "Hello. \n "       @ message
szRetourLigne:  .asciz "\n"
iValDeb:        .int 5      @ value 5 in array of 4 bytes
/* No Initialized data */
.bss
iValeur:     .skip  4     @ reserve 4 bytes in memory

.text
.global main 
main:	
        ldr r0,=szMessage          @ adresse of message  short program
	bl affichageMess            @ call function
	                                @  or
	ldr r0,iAdrszMessage         @ adresse of message big program (size code > 4K)
        bl affichageMess            @ call function
	
	ldr r1,=iValDeb              @ adresse of variable -> r1  short program
	ldr r0,[r1]                    @ value of iValdeb  -> r0
	ldr r1,iAdriValDeb           @ adresse of variable -> r1  big program
	ldr r0,[r1]                    @ value of iValdeb  -> r0

	
	/* set variables  */
	ldr r1,=iValeur               @ adresse of variable -> r1  short program
	str r0,[r1]                     @ value of r0 ->  iValeur
	ldr r1,iAdriValeur           @ adresse of variable -> r1  big program
	str r0,[r1]                     @ value of r0 ->  iValeur
 
 
 /* end of  program */
    mov r0, #0                  @ return code
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdriValDeb:  .int iValDeb	
iAdriValeur:  .int iValeur	
iAdrszMessage: .int szMessage
iAdrszRetourLigne: .int szRetourLigne	
/******************************************************************/
/*     affichage des messages   avec calcul longueur              */ 
/******************************************************************/
/* r0 contient l adresse du message */
affichageMess:
	push {fp,lr}    /* save des  2 registres */ 
	push {r0,r1,r2,r7}    /* save des autres registres */
	mov r2,#0   /* compteur longueur */
1:	      /*calcul de la longueur */
    ldrb r1,[r0,r2]  /* recup octet position debut + indice */
	cmp r1,#0       /* si 0 c est fini */
	beq 1f
	add r2,r2,#1   /* sinon on ajoute 1 */
	b 1b
1:	/* donc ici r2 contient la longueur du message */
	mov r1,r0        /* adresse du message en r1 */
	mov r0,#STDOUT      /* code pour écrire sur la sortie standard Linux */
    mov r7, #WRITE                  /* code de l appel systeme 'write' */
    swi #0                      /* appel systeme */
	pop {r0,r1,r2,r7}     /* restaur des autres registres */
	pop {fp,lr}    /* restaur des  2 registres */ 
    bx lr	        /* retour procedure */

Arturo

x: 2
xInfo: info.get 'x

print [
    "address of x:" xInfo\address 
    "->" from.hex xInfo\address
]
Output:
address of x: 0x109EAC228 -> 4461347368

Astro

var num = 12
var pointer = ptr(num) # get pointer

print pointer # print address

@unsafe # bad idea!
pointer.addr = 0xFFFE # set the address

AutoHotkey

Getting or setting the address of a variable is not supported as a builtin function. However, you can get the address of contents pointed to by the variable structure var

msgbox % &var

Axe

Axe supports getting the address of a variable using the degree symbol:

°A→B
.B now contains the address of A

Axe does not support setting the address of a variable directly. However, it does support setting the value of a variable and then dereferencing it:

1234→A
1→{A}

This should usually be avoided because TI-OS does not use virtual memory. Writing to arbitrary memory locations can affect the stability of the operating system.

BaCon

'---get a variable's address
LOCAL x TYPE long
PRINT ADDRESS(x)

BASIC

Many BASICs, especially older flavors like QuickBASIC, lack the ability to set a variable's address (and indeed, they pretty much all lack the ability to work with pointers in any fashion).

'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)

'can't set the address, but can access a given memory location... 1 byte at a time
DIM z AS INTEGER
z = PEEK(y)
z = z + (PEEK(y) * 256)

BBC BASIC

The original BBC BASIC doesn't provide an address-of operator, but BBC BASIC for Windows does:

REM get a variable's address:
y% = ^x%

REM can't set a variable's address, but can access a given memory location (4 bytes):
x% = !y%

With BBC BASIC on other platforms the address of a variable can be found by calling a short piece of machine code, see BeebWiki.

Beef

int i = 5;
int* p = &i;

Set the address:

int* p = (int*)((void*)0xDEADBEEF);


C / C++

Works with: gcc
Works with: g++

Get the address

Note that void* is a "pure" address which doesn't carry the type information anymore. If you need the type information (e.g. to recover the variable itself in a type safe manner), use a pointer to the appropriate type instead; in this case int*.

int i;
void* address_of_i = &i;

C++ only: C++ allows overloading the & operator. To bypass this, for example in generic code, use the library function addressof:

#include <memory>
int i;
auto address_of_i = std::addressof(i);

Set the address

While C++ doesn't directly support putting a variable at a given address, the same effect can be achieved by creating a reference to that address:

int& i = *(int*)0xA100;

If the type of the variable requires initialization, it is necessary to use placement new:

#include <new>
struct S { int i = 0; S() {} };
auto& s = *new (reinterpret_cast<void*>(0xa100)) S;

Overlaying of variables is done with anonymous unions; however at global/namespace scope such variables have to be static (i.e. local to the current file):

static union
{
  int i;
  int j;
};

C++ only: An alternative (and cleaner) solution is to use references:

int i;
int& j = i;

Note that in this case, the variables can be non-static.

If the type of two overlaid variables is not sufficiently similar, then writes to one may not be reflected in reads from the other, even though they have the same address. This is because the optimizer is free to assume that variables of different types do not alias. To read or write a variable as a different type, use memcpy:

#include <cstring>
inline float read_as_float(int const& i) { float f; memcpy(&f, &i, sizeof(f)); return f; }
int i = 0x0a112233;
float f = read_as_float(i);


C#

Use of pointers in C# is restricted to unsafe sections of code, which is enabled in Microsoft's C# compiler with the commandline parameter /unsafe or in Mono's C# compiler with -unsafe (or --unsafe in older versions).

Get the address

Note that void* is a "pure" address which doesn't carry the type information anymore. If you need the type information (e.g. to recover the variable itself in a type safe manner), use a pointer to the appropriate type instead; in this case int*.

unsafe
{
  int i = 5;
  void* address_of_i = &i;
}

COBOL

Pointers were added in COBOL 2002.

Get Address

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 ptr USAGE POINTER.
       01 var PIC X(64).
       
       PROCEDURE DIVISION.
           SET ptr TO ADDRESS OF var.

Set Address

Sets the address of a variable using the BASED clause. There are other methods, in particular LINKAGE SECTION variables.

OCOBOL*> Rosetta Code set address example
      *> tectonics: cobc -x setaddr.cob && ./setaddr
       IDENTIFICATION DIVISION.
       PROGRAM-ID. setaddr.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 prealloc PIC X(8) VALUE 'somedata'.
       01 var      PIC X(8) BASED.
       
       PROCEDURE DIVISION.
           SET ADDRESS OF var TO ADDRESS OF prealloc
           DISPLAY var END-DISPLAY 
      *>    'somedata'
           GOBACK.
       
       END PROGRAM setaddr.

Commodore BASIC

Works with: BASIC version 7.0 (C-128)

The address of a variable in BASIC is readonly, but accessible via the POINTER function.

100 REM ALLOCATE ALL VARS FIRST SO THEY DON'T MOVE
110 X=123:Y=456:PX=0:PY=0:I=0:T=0
120 PRINT "BEFORE:X="XCHR$(20)",Y="Y
130 PX=POINTER(X):PY=POINTER(Y)
140 REM VARS ARE STORED IN RAM BANK 1
150 BANK 1
160 FOR I=0 TO 6
170 : T = PEEK(PY+I)
180 : POKE PY+I,PEEK(PX+I)
190 : POKE PX+I,T
200 NEXT I
210 PRINT "AFTER: X="XCHR$(20)",Y="Y
Works with: BASIC version 2.0 (VIC-20, C-64)

With older machines, there's no built-in mechanism in BASIC to find a variable's address, but you can use the internal state of the BASIC interpreter to achieve similar results. Here's a VIC-20/C-64 version that works the same as the above C-128 program:

100 X=PEEK(71)+256*PEEK(72):PX=X:X=123
110 Y=PEEK(71)+256*PEEK(72):PY=Y:Y=456
120 PRINT "BEFORE:X ="XCHR$(20)", Y ="Y
130 FOR I=0 TO 6
140 : T = PEEK(PY+I)
150 : POKE PY+I,PEEK(PX+I)
160 : POKE PX+I,T
170 NEXT I
180 PRINT "AFTER: X ="XCHR$(20)", Y ="Y

They same idea should work on other Commodore computers as well, though at least the address being PEEKed will have to change.

Output:
BEFORE:X= 123,Y= 456
AFTER: X= 456,Y= 123

Common Lisp

Simulated Address of Variable

Common Lisp has no means to take a simple address reference to a place (the Lisp term for any one of many types of assignable storage locations). For instance, to access the slot of a structure, we need the structure itself (which is essentially a pointer) and a symbol denoting the slot name. To access an array, we need that array object, and an index. To access a local variable, we need the closure object, which is only accessible to code within the lexical scope, which is a long-winded way of saying, we can only access a variable via an expression which is in the lexical scope of the variable.

Yet, thanks to Lisp macros and lexical closures, we can create reference values which behave like address of places. A tiny module for doing this is found in Lisppaste #71952 (now it's available here), required by the following example:

;;; Demonstration of references by swapping two variables using a function rather than a macro
;;; Needs http://paste.lisp.org/display/71952
(defun swap (ref-left ref-right)
  ;; without with-refs we would have to write this:
  ;; (psetf (deref ref-left) (deref ref-right)
  ;;        (deref ref-right) (deref ref-left))
  (with-refs ((l ref-left) (r ref-right))
    (psetf l r r l)))

(defvar *x* 42)
(defvar *y* 0)

(swap (ref *x*) (ref *y*))

;; *y* -> 42
;; *x* -> 0

These references are completely safe to use. There is no way that a place can disappear, leaving a reference dangling, because if a reference is a live object, it prevents the object which contains the referenced place from becoming garbage. Also note that if two references are taken to the same memory location, they are two distinct objects. A function could be provided to test two references for referential equality (do they point to the same object).

Varible-Like Moniker for External Location

Works with: CLISP
Works with: Linux
Works with: Cygwin

What does it mean to "set the address of a variable?" One interpretation of this task is: rather than let the programming language compiler or run-time allocate a named storage location in its usual ways, force the allocation of a variable at some particular memory location, such as a hardware register, or a variable in a foreign library. Lisp implementations have foreign function interfaces for doing this sort of thing.

Here is an example specific to CLISP running on either Linux or Cygwin. It creates a Lisp errno variable which is located in the C Library's errno. The C Library's errno is actually thread-specific, whose location is retrieved by calling a hidden function.

We wrap this function with a Lisp foreign call which is properly annotated as returning a C pointer to int. When we call this function, we get an object that behaves like a reference to that location. All we need then is a macro which looks like a storage location.

(use-package :ffi)

(defmacro def-libc-call-out (name &rest args)
  `(def-call-out ,name
     (:language :stdc)
     #-cygwin(:library "libc.so.6")
     #+cygwin (:library "cygwin1.dll")
     ,@args))

(progn
  (def-libc-call-out errno-location
    #-cygwin (:name "__errno_location")
    #+cygwin (:name "__errno")
    (:arguments)
    (:return-type (c-pointer int)))

  (defun get-errno ()
    (let ((loc (errno-location)))
      (foreign-value loc)))

  (defun set-errno (value)
    (let ((loc (errno-location)))
      (setf (foreign-value loc) value)))

  (defsetf get-errno set-errno)

  (define-symbol-macro errno (get-errno)))

Test:

[1]> (setf errno 42)
42
[2]> errno
0   ;; Oops! the REPL itself executed a bunch of code which cleared errno
[3]> (progn (delete-file "nonexistent") errno)
2   ;; Aha! 2 is ENOENT: No such file or directory

Component Pascal

BlackBox Component Builder

MODULE AddressVar;
IMPORT SYSTEM,StdLog;

VAR
	x: INTEGER;
	
PROCEDURE Do*;
BEGIN
	StdLog.String("ADR(x):> ");StdLog.IntForm(SYSTEM.ADR(x),StdLog.hexadecimal,8,'0',TRUE);StdLog.Ln
END Do;

BEGIN
	x := 10;
END AddressVar.

Execute: ^Q AddressVar.Do

Output:
ADR(x):> 653700D8H

Creative Basic

== Get ==

To get the address of a variable without using the Windows API:

DEF X:INT
DEF pPointer:POINTER
pPointer=X

----

To get the address of a variable using the Windows API Lstrcpy function called in Creative Basic:
(This may give users of another language without a native way to get the address of a variable to work around that problem.)

DEF Win:WINDOW
DEF Close:CHAR
DEF ScreenSizeX,ScreenSizeY,Col:INT

'***Map Function***
DECLARE "Kernel32",Lstrcpy(P1:POINTER,P2:POINTER),INT
'The pointers replace the VB3 variable type of Any.

'Note: This is translated from VB3 or earlier code, and "Ptr" is *not* a Creative Basic pointer. 
DEF Ptr:INT
DEF X1:INT
DEF X2:STRING

X1=123

'***Call function***   
Ptr=Lstrcpy(X1,X1)
     
GETSCREENSIZE(ScreenSizeX,ScreenSizeY)

WINDOW Win,0,0,ScreenSizeX,ScreenSizeY,@MINBOX|@MAXBOX|@SIZE|@MAXIMIZED,0,"Skel Win",MainHandler

'***Display address***
PRINT Win, "The address of x1 is: " + Hex$(Ptr)
      X2="X2"

WAITUNTIL Close=1

CLOSEWINDOW Win

END

SUB MainHandler

	SELECT @CLASS

	CASE @IDCLOSEWINDOW

	Close=1

	ENDSELECT

RETURN

Note: The Windows Dev Center (http://msdn.microsoft.com/en-us/library/windows/desktop/ms647490%28v=vs.85%29.aspx) says
improper use of the Lstrcpy function may compromise security. A person is advised to see the Windows Dev site before using
the Lstrcopy function.

== Set ==

It appears to the author the closest one can come to setting the address of a variable is to set which bytes will be
used to store a variable in a reserved block of memory:

DEF pMem as POINTER
pMem = NEW(CHAR,1000) : 'Get 1000 bytes to play with
#<STRING>pMem = "Copy a string into memory"
pMem += 100
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem

D

Take the address of a variable:

int i;
int* ip = &i;

Using a numeric value:

int* ip = cast(int*)0xdeadf00d;

Locating a "regular" variable at a specific address is not possible.

The closest thing is passing a dereferenced pointer to a reference parameter.

void test(ref int i) {
    import std.stdio;
    writeln(&i);
}

void main() {
    test(* (cast(int*)0xdeadf00d) );
}

Delphi

Turbo/Borland Pascal and Delphi (Object Pascal) support the @ (address of) operator and the var: [type] absolute declaration.

To get the address of any variable, structure, procedure or function use the @-operator:

var
	i: integer;
	p: ^integer;
begin
	p := @i;
	writeLn(p^);
end;

Note, (untyped) constants do not have an address in Pascal.

A variable can be declared as absolute i. e.: to reside at a specific address:

var
	crtMode: integer absolute $0040;
	str: string[100];
	strLen: byte absolute str;

Draco

/* This code uses a CP/M-specific address to demonstrate fixed locations,
 * so it will very likely only work under CP/M */
proc nonrec main() void:
    /* When declaring a variable, you can let the compiler choose an address */
    word var;   
    
    /* Or you can set the address manually using @, to a fixed address */
    word memtop @ 0x6;     /* CP/M stores the top of memory at 0x0006 */ 
    
    /* or to the address of another variable, by naming that variable */
    word var2 @ var;       /* var2 will overlap var */
    
    /* This works with both automatically and manually placed variables. */
    word memtop2 @ memtop; /* same as "memtop2 @ 0x6" */
    
    /* Once a variable is declared, you can't change its address at runtime. */
    
    var := 1234;           /* assign a value to var _and_ var2 */
    
    /* The address of a variable can be retrieved using the & operator. 
     * However, this returns a pointer type, which is distinct from an
     * integer type. To use it as a number, we have to coerce it to an integer
     * first. */     
    writeln("var     address=", pretend(&var,word):5,     " value=", var:5);
    writeln("memtop  address=", pretend(&memtop,word):5,  " value=", memtop:5);
    writeln("var2    address=", pretend(&var2,word):5,    " value=", var2:5);
    writeln("memtop2 address=", pretend(&memtop2,word):5, " value=", memtop2:5)
corp
Output:
var     address=  276 value= 1234
memtop  address=    6 value=58374
var2    address=  276 value= 1234
memtop2 address=    6 value=58374

ERRE

ERRE hasn't explicit pointers, but only a function that gets the address of a variable

........
A%=100
ADDR=VARPTR(A%)
.......

ADDR contains the value of the address of variable A (from 0 to 65535 because every ERRE module has a 64K address space). ERRE data types is 2 bytes-long for integer, 4 (5 with C-64) for reals and 8 for double-real variables. Using this address you can modify the variable's value without using an assignment statement:

PROGRAM POINTER
BEGIN
   A%=100
   ADDR=VARPTR(A%)
   PRINT(A%)       ! prints 100
   POKE(ADDR,200)
   PRINT(A%)       ! prints 200
END PROGRAM

Note: With C-64 substitute POKE(ADDR,200) with POKE(ADDR+3,200).

FBSL

Unlike in other BASICs, pointers are readily available in FBSL in several ways although C-style pointer arithmetics is not supported.

1. A simple Variant variable may be dereferenced to point to any other FBSL entity from simple variables through arrays to class instances and COM objects with a ReferenceOf operator, e.g.

   ReferenceOf a = b

whereby a is set to refer to the variable b.

2. Non-function entities' pointers can be both retrieved and set using a PointerOf operator which also has a shorthand alias @, e.g.

   @a = @b

whereby a is set to refer to the variable b. Assignment through the PointerOf operator also accepts integer literals to set the variable's absolute address to.

3. Function pointers can be both retrieved and set using an AddressOf operator as in the following sample script. Assignment via AddressOf also accepts integer literals to set a function pointer to an absolute address.

   #APPTYPE CONSOLE
   
   SUB Foo()
       PRINT "foo"
   END SUB
   
   SUB Bar()
       PRINT "bar"
   END SUB
   
   ADDRESSOF Foo = ADDRESSOF Bar
   
   Foo() // prints "bar" to the console
   
   PAUSE

4. Values at an absolute address or address read by a PointerOf operator plus a byte offset can be retrieved or set using the Peek()/Poke() and GetMem()/SetMem() functions.

Forth

Variables and created memory blocks return their address when referenced. The "fetch" operator @ could also be pronounced "dereference".

variable foo
foo .  \ some large number, an address
8 foo !
foo @ .  \ 8

You can define a constant or value with an address, which then acts like a variable. This can be used to refer to fixed addresses (such as I/O ports), graphics buffers, or allocated memory.

$3F8 constant LPT1:
8 LPT1: !
100 cells allocate throw value buffer
42 buffer 20 cells + !

Fortran

Works with: Fortran version 90 and later
program test_loc
  implicit none

  integer :: i
  real    :: r

  i = loc(r)
  print *, i
end program

Note: loc is a common extension that is implemented by e.g. the Intel Fortran Compiler, G95 and gfortran.

FreeBASIC

One can get the address of a variable using the @ operator:

' FB 1.05.0 Win64
Dim a As Integer = 3
Dim p As Integer Ptr = @a
Print a, p

To my knowledge, it is not possible to set the address of a variable to a specific address in FB though (as in C/C++) you can do something like this as a workaround:

Var p = Cast(Integer Ptr, 1375832)
*p = 42
Print p, *p

FutureBasic

window 1

short i = 575
ptr j

j = @i

printf @"Address of i = %ld",j
print @"Value of i = ";peek word(j)

HandleEvents

Output:

Adddress of i = 4330713552
Value of i = 575

GDScript

Works with: Godot version 4.0

GDScript does not expose addresses, however there are reference identifiers (RIDs).

extends MainLoop


func _process(_delta: float) -> bool:
	var a := Node.new()
	var b := Node.new()

	# a and b are different objects with different RIDs
	print(a.get_instance_id())
	print(b.get_instance_id())

	assert(a != b)
	assert(a.get_instance_id() != b.get_instance_id())

	# Set b to refer to the same object as a
	b.free()
	b = a

	# a and b are now the same object and have the same RID
	print(a.get_instance_id())
	print(b.get_instance_id())

	assert(a == b)
	assert(a.get_instance_id() == b.get_instance_id())

	a.free()
	return true # Exit

Go

Go has pointers. Just like in C, you can "take the address" of an addressable value by using the & operator, and access the value pointed to by a pointer using the * operator.

Unlike in C, pointers are not readily convertible to integers and there is no direct pointer arithmetic. You may print out the address of a pointer, either using the Print function on the pointer, or using the %p format specifier in formatted output (just like in C).

When rarely required, you can convert a pointer to an integer using the unsafe package.

It is not possible in Go to set the address of a variable, however you can assign an arbitrary value to a pointer and use/deference that pointer.

The following demonstrates getting the address of a variable and storing/printing it various ways. It also demonstrates accessing an arbitrary memory location (here the known address of a float) as an integer.

package main

import (
	"fmt"
	"unsafe"
)

func main() {
	myVar := 3.14
	myPointer := &myVar
	fmt.Println("Address:", myPointer, &myVar)
	fmt.Printf("Address: %p %p\n", myPointer, &myVar)

	var addr64 int64
	var addr32 int32
	ptr := unsafe.Pointer(myPointer)
	if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
		addr64 = int64(uintptr(ptr))
		fmt.Printf("Pointer stored in   int64: %#016x\n", addr64)
	}
	if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) {
		// Only runs on architectures where a pointer is <= 32 bits
		addr32 = int32(uintptr(ptr))
		fmt.Printf("Pointer stored in   int32: %#08x\n", addr32)
	}
	addr := uintptr(ptr)
	fmt.Printf("Pointer stored in uintptr: %#08x\n", addr)

	fmt.Println("value as float:", myVar)
	i := (*int32)(unsafe.Pointer(&myVar))
	fmt.Printf("value as int32: %#08x\n", *i)
}
Output:

On a 32 bit architecture:

Address: 0x3826c020 0x3826c020
Address: 0x3826c020 0x3826c020
Pointer stored in   int64: 0x000000003826c020
Pointer stored in   int32: 0x3826c020
Pointer stored in uintptr: 0x3826c020
value as float: 3.14
value as int32: 0x51eb851f

On a 64 bit architecture:

Address: 0xc208000170 0xc208000170
Address: 0xc208000170 0xc208000170
Pointer stored in   int64: 0x000000c208000170
Pointer stored in uintptr: 0xc208000170
value as float: 3.14
value as int32: 0x51eb851f

IWBASIC

== Get ==

There are at least three ways to get the address of a variable in IWBASIC. The first is to use the address of operator:

DEF X:INT
PRINT &X
'This will print in the console window (after OPENCONSOLE is issued.) 
'To Print in an open window the appropriate Window variable is specified, e.g., PRINT Win,&X.

The second is to use a pointer:

DEF X:INT
DEF pPointer:POINTER
pPointer=X

The third is to use the Windows API function Lstrcpy. That is done in the same way as the Creative Basic example;
however, the function would be declared as follows: DECLARE IMPORT,Lstrcpy(P1:POINTER,P2:POINTER),INT.

== Set ==

It appears to the author that the closest one can come to being able to assign an address to a variable is to set
which bytes will be used to store a variable in a block of reserved memory:

DEF pMem as POINTER
pMem = NEW(CHAR,1000) : 'Get 1000 bytes to play with
#<STRING>pMem = "Copy a string into memory"
pMem += 100
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem

J

J hides the details of pointers and memory allocation from the programmer, so it is rarely, if ever, necessary to do this. However, for those times when there is no better substitute, J provides access to these low-level details:

   var      =: 52                NB.  Any variable (including data, functions, operators etc)
   var_addr =: 15!:6<'var'       NB.  Get address
   new_var  =: 15!:7 var_addr    NB.  Set address

Java

There is no way to access addresses of variables in Java. However, the default hashCode() method defined in the Object class, "is typically implemented by converting the internal address of the object into an integer". Therefore, in some Java implementations at least, the hash code returned by Object.hashCode() reflects at least part of the address of an object. For objects whose classes have overridden the hashCode() method, you can still access the original hash code through the System.identityHashCode() function.

Julia

Julia provides a variety of ways to work with and manipulate raw address pointers (via the built-in Ptr type), which are mostly used in practice for calling C library functions.

Julia has both mutable and immutable objects. Immutable objects are values, such as constants, bit-based values such as numeric 3, or immutable structs. Immutable objects may not have a single set location in memory, but instead might in some cases be created on demand by the compiled code. Mutable objects such as typical arrays and mutable structs, on the other hand, have addresses on the Julia heap that can be found with specific base Julia functions which use the Ptr type.

To get the memory address of a Julia object, one can use pointer_from_objref(object), and the reverse is accomplished by unsafe_pointer_to_objref(ptr):

julia> x = [1, 2, 3]
julia> ptr = pointer_from_objref(x)
Ptr{Void} @0x000000010282e4a0
julia> unsafe_pointer_to_objref(ptr)
3-element Array{Int64,1}:
 1 
 2 
 3

The latter is "unsafe" because it only works if ptr refers to a valid heap-allocated "boxed" Julia object, which can only be safely allocated by Julia itself.

Another common use of pointers is for arrays of values, which are typically passed in low-level C-like libraries via pointers to contiguous sets of values in memory. This is accomplished in Julia by the pointer(A) function, which returns a pointer to the data stored in a high-level Julia array A. Given a pointer p to values of a given type, the i-th value (numbered starting at 1 for the value pointed to by p) can be read or written by the low-level unsafe_load(p, i) and unsafe_store!(p, val, i) functions, or it can be converted back to a high-level Julia array type by the pointer_to_array(p, dimensions) function:

julia> A = [1, 2.3, 4]
3-element Array{Float64,1}:
 1.0
 2.3
 4.0

julia> p = pointer(A)
Ptr{Float64} @0x0000000113f70d60

julia> unsafe_load(p, 3)
4.0

julia> unsafe_store!(p, 3.14159, 3)
julia> A
3-element Array{Float64,1}:
 1.0    
 2.3    
 3.14149

julia> pointer_to_array(p, (3,))
3-element Array{Float64,1}:
 1.0    
 2.3    
 3.14149

Finally, an arbitrary integer can be converted to a pointer type with convert, which allows an arbitrary address to be converted into and viewed as an array of an arbitrary type and read or written (although this can easily result in a crash if an invalid address is used). In the following example, we create a "new" length-two array B at an address offset by 8 bytes from the address of the data in A above, which will make it point to the second element of A:

julia> 
julia> q = convert(Ptr{Float64}, 0x0000000113f70d68)
Ptr{Float64} @0x0000000113f70d68

julia> B = pointer_to_array(q, (2,))
2-element Array{Float64,1}:
 2.3    
 3.14149


Kotlin

Kotlin/JVM does not support pointers and so (apart from some jiggery-pokery with the sun.misc.Unsafe class) there is no way to obtain a variable's address.

However, Kotlin/Native which is currently (January 2018) available as a pre-release version does support pointers to enable it to interoperate with C code. The following program shows how to obtain the address of a variable which has been allocated on the native heap. It does not appear to be possible to allocate a variable at a particular address.

Works with: Ubuntu version 14.04
// Kotlin Native v0.5

import kotlinx.cinterop.*

fun main(args: Array<String>) {
    val intVar = nativeHeap.alloc<IntVar>()
    intVar.value = 42
    with(intVar) { println("Value is $value, address is $rawPtr") }
    nativeHeap.free(intVar)
}
Output:

Sample output:

Value is 42, address is 0xc149f0

Lambdatalk

In Lambdatalk expressions are made of words and S-expressions. Words have no address, they stay unevaluated. S-expressions built with the [lambda, quote|', pair, array] keywords, are replaced by words [_LAMB_xx, _QUOT_xx, _PAIR_xx, _ARRA_xx] - where xx is any positive system computed integer - which are references to functions stored in four dictionaries, [LAMB, QUOT, PAIR, ARRA]. Users are not supposed to access these addresses. During the post-processing phase the addresses which have not been "consumed" by the evaluation are automatically evaluated to show the related values in a convenient way. For instance:

1) lambdas

{lambda {:x} {* :x :x}}
-> _LAMB_123

2) arrays

'{A.new hello world}  // defining an array
-> _ARRA_123          // as replaced and used before post-processing
-> [hello,world]      // if unused after post-processing

3) pairs

{pre
'{P.new hello world}  // defining a pair
-> _PAIR_123          // as replaced and used before post-processing
-> (hello world)      // if unused after post-processing

4) quotes
 
'{+ 1 2}              // protecting an expression
-> _QUOT_124          // as replaced and protected before post-processing
-> {+ 1 2}            // as displayed after post-processing

Lua

Pure/native Lua does not support true pointer operations. Memory management is automatic, and garbage-collected, so at best you can hold a temporary reference to the allocated memory. However the "virtual address" of complex types is discoverable (and is in fact how the internals deal with assignment, equality testing, etc), and userdata types typically reveal an actual physical address.

t = {}
print(t)
f = function() end
print(f)
c = coroutine.create(function() end)
print(c)
u = io.open("/dev/null","w")
print(u)
print(_G, _ENV) -- global/local environments (are same here)
print(string.format("%p %p %p", print, string, string.format)) -- themselves formatted as pointers
Output:
table: 00000000001d93b0
function: 00000000001dcb30
thread: 00000000001de088
file (00007ffe2612fa90)
table: 00000000001d1e80 table: 00000000001d1e80
0000000065b9cd60 00000000001d90b0 0000000065ba34f0

Maple

To obtain the address of any expression in Maple, use the builtin function addressof.

> addressof( x );             
                              18446884674469911422

The inverse operation is pointto:

> pointto( 18446884674469911422 );
                                       x

This works for any expression, not just variables:

> addressof( sin( x )^2 + cos( x )^2 );
                              18446884674469972158

> pointto( 18446884674469972158 );
                                     2         2
                               sin(x)  + cos(x)

M2000 Interpreter

From version 12, VarPtr() can return address for variables and array items.

We can't set an address to a variable. We can link a variable name with an existing variable. Is the same as passing by reference.

module checkVarptr {
	declare GetMem8 lib "msvbvm60.GetMem8" {Long addr, Long retValue}
	long long x=1234567812345678&&, z
	dim k(2,2,2) as long long
	call GetMem8(VarPtr(x), VarPtr(z))
	call GetMem8(VarPtr(x), VarPtr(k(1,0,1)))
	print z=x
	print k(1,0,1)=x
	link z to m
	print VarPtr(z)=VarPtr(m)
	checkref(&z)
	sub checkref(&p)
		print VarPtr(z)=VarPtr(p)
	end sub
}
checkVarptr
module checkVarptr {
	// Using byref at GemMem8 signature
	declare GetMem8 lib "msvbvm60.GetMem8" {long &addr, long &retValue}
	declare PutMem8 lib "msvbvm60.PutMem8" {long &addr, retValue as long long}
	long long x=1234567812345678&&, z
	dim k(2,2,2) as long long
	call GetMem8(&x, &z)
	call GetMem8(&x, &k(1,0,1))
	print z=x
	print k(1,0,1)=x
	checkref(&z)
	print z=987654321987654321&&
	sub checkref(&p)
		print VarPtr(z)=VarPtr(p)
		call PutMem8(&p, 987654321987654321&&)
	end sub
}
checkVarptr
Output:
True
True
True
True

Modula-2

Get Address

MODULE  GetAddress;

FROM    SYSTEM IMPORT ADR;
FROM    InOut  IMPORT WriteInt, WriteLn;

VAR     var : INTEGER;
        adr : LONGINT;
BEGIN
    adr := ADR(var);    (*get the address*)
    WriteInt(adr, 0);
    WriteLn;
END GetAddress.

Set Address

MODULE  SetAddress;

CONST   adress  = 134664460;

VAR     var [adress] : INTEGER;

BEGIN
    (*do nothing*)
END SetAddress.

Nanoquery

Get Address

import native

a = 5

println format("0x%08x", native.address(a))
Output:
0xc46be580

Set Address

We cannot directly modify the address of a variable that has already be created, but we can create a pointer and move it to point at a different address.

import native

a = 123
b = 456

ptr = native.address(a)
println native.object(ptr)

ptr = native.address(b)
println native.object(ptr)
Output:
123
456

NewLISP

Get Address

(set 'a '(1 2 3))
(address a)

Nim

var x = 12
var xptr = addr(x) # Get address of variable
echo cast[int](xptr) # and print it
xptr = cast[ptr int](0xFFFE) # Set the address

Oberon-2

Get Address

VAR a: LONGINT;
VAR b: INTEGER;

b := 10;
a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)

Set Address

SYSTEM.PUT(a, b); (* Sets the address of b to the address of a *)

OCaml

OCaml is a high-level programming language, and thus does not expose the addresses of variables to the programmer.

However, it is kind of possible to get the address of the structure pointed to by a reference type. At runtime, every value in OCaml is a pointer to a "block" structure (i.e. boxed) except for int (and things that can fit inside an int, like char, bool, None, datatypes with all no-arg constructors, etc.) which is a direct value (unboxed). For boxed types, it is possible to get this address by some tricky hacks.

An OCaml value is distinguished between an unboxed integer and a boxed type by the last (least significant) bit. If the bit is set (1), then the value is an integer, and the rest of the bits are the bits of the integer, shifted one bit to the left (that's why int in OCaml can only represent 31 bits in 32-bit, and 63 bits in 64-bit). If the last bit is cleared (0), then the value is a pointer, and all the bits (including the last one) form the address.

To get the address, we re-interpret the boxed value as an integer; however, this will get the address divided by 2, since the integer only uses the upper 31 (or 63) bits. Therefore, we need to shift this number left by one to get the real address. However, int cannot hold all the bits of the address, so if we shift we will lose a bit, so we use the nativeint type to represent it instead:

let address_of (x:'a) : nativeint =
  if Obj.is_block (Obj.repr x) then
    Nativeint.shift_left (Nativeint.of_int (Obj.magic x)) 1 (* magic *)
  else
    invalid_arg "Can only find address of boxed values.";;

let () =
  let a = 3.14 in
  Printf.printf "%nx\n" (address_of a);;
  let b = ref 42 in
  Printf.printf "%nx\n" (address_of b);;
  let c = 17 in
  Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *)

Odin

package main

main :: proc() {
  i : int = 42
  ip : ^int = &i                  // Get address of variable

  address := uintptr(0xdeadf00d)
  ip2 := cast(^int)address        // Set the address
}

Oforth

In Oforth, addresses are not exposed.

Variables (like all Oforth metamodel) are objects. It is possible to retrieve the object corresponding to a variable and use #at and #put to change its value.

For instance, here, after creating and setting a variable A, we store the corresponding word into a variable B :

tvar: A
10 to A

tvar: B
#A to B
B .s
[1] (Variable) #A
>ok

12 B put
A .s
[1] (Integer) 12
[2] (Variable) #A
>ok

Ol

Otus Lisp has no means to take a simple address reference to a place (the Lisp term for any one of many types of assignable storage locations). It can be done only using the extension mechanism (ffi), but in any case this information can't be useful due to Garbage Collection (at any time the variable can be moved to other place that automatically makes invalid the got reference pointer).

ooRexx

ooRexx is a high-level programming language, and thus does not expose the addresses of variables to the programmer. Variables can be accessed by name using the VAR(), SYMBOL(), and VALUE() built-in functions.

OxygenBasic


'GETTING ADDRESS OF VARIABLE

int a=1,b=2,c=3
print "Adrress of b: " @b


'SETTING ADDRESS OF INDIRECT (BYREF) VARIABLE

int *aa,*bb,*cc

@bb=@b 'setting address of bb to address of b

print "Value of bb: " bb 'result: 2

Panoramic

== Get ==

adr(variable)

Example:

dim a
print adr(a)

== Set ==

Whether Panoramic is able to set the value of a variable may depend on what is meant by that. Panoramic implements the
poke command to set a byte from a value of 0 to 255 (inclusive). Panoramic also implements the peek command to get
the value of a byte, so it is possible to the following:
 
(A)
dim a
rem a variable with no post-fix is a real. 
poke adr(a),57
rem the value of a variable being set by setting an address, the address of a in this instance.

(B)
dim a%,b%
rem % means integer.
b%=57
poke adr(a%),b%
rem b% being assigned to the address of a%, in this instance.
rem it is even possible to free b%
free b%
print a%

(C)
dim a,b
b=57
poke adr(a),b
b=peek(adr(a))
print b
rem the address of b being, in effect, set to the address of a, the address of a, in this instance.

rem Observations and further insight welcome.

''Note:'' An attempt to poke a real or an integer (Panoramic's only numeric types) value of less than 0 or of more than
255 will cause an error.

PARI/GP

In GP you can sent the address to built-in commands like issquare

issquare(n, &m)

but you cannot directly compute with it. You can view the address of a variable and other debugging information with the

\x

command.

In PARI you can use standard C commands.

Pascal

See Delphi

Perl

To get the address, get the reference to a variable, and either stringify it, or use Scalar::Util's refaddr() to get just the address. Also see Devel::Peek.

use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n";  # 140502490125712

Alternatively, the address (in hexadecimal) can be directly obtained with printf:

printf "%p", $v; # 7fc949039590

Use Devel::Pointer::PP if you want to dereference a certain address in memory.

Changing the address of a variable is not easily possible, but see perlapi. Wanting to go against the automatic memory management is a sign that this is only used to hack around the deficiencies of dafter languages. I can imagine address munging is commonly used to make variable aliasing possible, but Perl already has a higher level syntax for that.

Simple reference (address) manipulation.

my $a = 12;
my $b = \$a; # get reference
$$b = $$b + 30; # access referenced value
print $a; # prints 42

Example how to make variable overlay.

my $a = 12;
our $b; # you can overlay only global variables (this line is only for strictness)
*b = \$a;
print $b; # prints 12
$b++;
print $a; # prints 13

Phix

Phix does not natively support pointers, but there are methods to do whatever you need.
You cannot set the address of a variable, but you can save it and use that to modify things.
Things get more complicated for floats/strings/sequences, particularly wrt reference counts, but there are examples aplently, for pretty much everything, in the builtins/VM sources. Since all hll variables are dword-aligned or better, a shr 2 loses no information and the result can be safely stored in an integer, avoiding some nasty int/float conversions for anything above #3FFFFFFF (on 32 bit, add another 8Fs on 64 bit). Obviously extreme caution must be exercised, in the example below if you save the address of V which is local to the address() procedure, and then exit said, you have a pointer to memory that will be re-used for something completely different almost immediately. Example is 32 and 64 bit compatible, which at this level needs twice the code, however the compiler only omits the appropriate binary for the currently selected target architecture. You can also use allocate/free with peek/poke to obtain similar effects.

procedure address()
object V
integer addr4   -- stored /4 (assuming dword aligned, which it will be)
#ilASM{
    [32]
        lea eax,[V]
        shr eax,2
        mov [addr4],eax
    [64]
        lea rax,[V]
        shr rax,2
        mov [addr4],rax
    []
      }
    if machine_bits()=32 then
        poke4(addr4*4,123)
    elsif machine_bits()=64 then
        poke8(addr4*4,123)
    end if
    ?V
    if getc(0) then end if
end procedure
 
address()
Output:
123

PicoLisp

The PicoLisp function 'adr' returns the address of a variable. A variable may be either a symbol or a cons pair in PicoLisp.

The returned address is a number representing an encoded pointer. For symbols, it is a negative number, and for cons pairs a positive number. The same function 'adr' can then be used to convert that pointer back to the original object.

: (setq X 7)
-> 7

: (adr 'X)  
-> -2985527269106

: (val (adr -2985527269106))
-> 7

: (set (adr -2985527269106) '(a b c))
-> (a b c)

: X                                  
-> (a b c)

PL/I

declare addr   builtin; /* retrieve address of a variable               */
declare ptradd builtin; /* pointer addition                             */
declare cstg   builtin; /* retrieve length of the storage of a variable */
declare hbound builtin; /* retrieve the number of elements in an array  */

declare p pointer;
declare i bin fixed(31) init(42);
p = addr(i); /* Obtain address of variable, stored in integer variable k */

/* how to read a string bit by bit - example for pointerAdd           */
/* we built a pointer (movingPointer), which will move through the    */
/*   storage of a variable (exampleTxt). attached to the pointer is   */
/*   an array of bits (movingBit) - this means wherever the pointer   */
/*   is pointing to, this will also be the position of the array.     */
/* only whole bytes can be addressed. to get down to the single bits, */
/*   an array of 8 bits is used.                                      */

declare exampleTxt    char(16) init('Hello MainFrame!);
declare movingPointer pointer;
declare movingBit(8)  bit(01) based(movingPointer);

declare walkOffset    bin fixed(31);
declare walkBit       bin fixed(31);

do walkOffset = 0 to cstg(exampleTxt)-1;
  movingPointer = ptradd(addr(exampleTxt, walkOffset);

  do walkBit = 1 to hbound(movingBit);
    put skip list( 'bit at Byte '  !!walkOffset
                 !!' and position '!!walkBit
                 !!' is '          !!movingBit(walkBit));
  end;
end;

PL/M

100H:
/* THERE IS NO STANDARD LIBRARY
   THIS DEFINES SOME BASIC I/O USING CP/M */
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PUT$CHAR: PROCEDURE (C); DECLARE C BYTE; CALL BDOS(2,C); END PUT$CHAR;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
NEWLINE: PROCEDURE; CALL PRINT(.(13,10,'$')); END NEWLINE;

/* PRINT 16-BIT HEX VALUE (POINTER) */
PRINT$HEX: PROCEDURE (N);
    DECLARE N ADDRESS, (I, C) BYTE;
    DO I=0 TO 3; 
        IF I <> 3 THEN C = SHR(N,12-4*I) AND 0FH;
        ELSE C = N AND 0FH;
        IF C >= 10 THEN C = C - 10 + 'A';
        ELSE C = C + '0';
        CALL PUT$CHAR(C);
    END;
END PRINT$HEX;

/* OF COURSE WE WILL NEED SOME VALUES TO POINT AT TOO */
DECLARE FOO ADDRESS INITIAL (0F00H);
DECLARE BAR ADDRESS INITIAL (0BA1H);

/* OK, NOW ON TO THE DEMONSTRATION */

/* THE ADDRESS OF A VARIABLE CAN BE RETRIEVED BY PREPENDING IT WITH A
   DOT, E.G.: */
CALL PRINT(.'FOO IS $'); CALL PRINT$HEX(FOO);
CALL PRINT(.' AND ITS ADDRESS IS $'); CALL PRINT$HEX(.FOO); 
CALL NEWLINE;

CALL PRINT(.'BAR IS $'); CALL PRINT$HEX(BAR);
CALL PRINT(.' AND ITS ADDRESS IS $'); CALL PRINT$HEX(.BAR);
CALL NEWLINE;

/* PL/M DOES NOT HAVE C-STYLE POINTERS. INSTEAD IT HAS 'BASED' VARIABLES. 
   
   WHEN A VARIABLE IS DECLARED 'BASED', ITS ADDRESS IS STORED IN ANOTHER 
   VARIABLE. 
   
   NOTE HOWEVER THAT THE 'ADDRESS' DATATYPE IS SIMPLY A 16-BIT INTEGER,
   AND DOES NOT INTRINSICALLY POINT TO ANYTHING. 
   
   THE FOLLOWING DECLARES A VARIABLE 'POINTER', WHICH WILL HOLD AN ADDRESS,
   AND A VARIABLE 'VALUE' WHICH WILL BE LOCATED AT WHATEVER THE VALUE IN
   'POINTER' IS. */
   
DECLARE POINTER ADDRESS;
DECLARE VALUE BASED POINTER ADDRESS;

/* WE CAN NOW ACCESS 'FOO' AND 'BAR' THROUGH 'VALUE' BY ASSIGNING THEIR
   ADDRESSES TO 'POINTER'. */
POINTER = .FOO;
CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER);
CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;
   
POINTER = .BAR;
CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER);
CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;

/* MUTATION IS ALSO POSSIBLE OF COURSE */
VALUE = 0BA3H;
CALL PRINT(.'VALUE IS NOW $'); CALL PRINT$HEX(VALUE);
CALL PRINT(.' AND BAR IS NOW $'); CALL PRINT$HEX(BAR); CALL NEWLINE;

/* LASTLY, PL/M SUPPORTS ANONYMOUS CONSTANTS.
   YOU CAN TAKE THE ADDRESS OF AN IMMEDIATE CONSTANT, AND PL/M
   WILL STORE THE CONSTANT IN THE CONSTANT POOL AND GIVE YOU ITS
   ADDRESS. THE CONSTANT MUST HOWEVER BE A BYTE OR A LIST OF BYTES. */
POINTER = .(0FEH,0CAH); /* NOTE THE DOT, AND THE LOW-ENDIAN 16-BIT VALUE */
CALL PRINT(.'POINTER IS $'); CALL PRINT$HEX(POINTER);
CALL PRINT(.' AND VALUE IS $'); CALL PRINT$HEX(VALUE); CALL NEWLINE;

/* NOTE THAT THIS IS ALSO HOW STRINGS WORK - SEE ALL THE DOTS IN FRONT
   OF THE STRINGS IN THE 'PRINT' CALLS */
CALL EXIT;
EOF
Output:
FOO IS 0F00 AND ITS ADDRESS IS 03FA
BAR IS 0BA1 AND ITS ADDRESS IS 03FC
POINTER IS 03FA AND VALUE IS 0F00
POINTER IS 03FC AND VALUE IS 0BA1
VALUE IS NOW 0BA3 AND BAR IS NOW 0BA3
POINTER IS 034D AND VALUE IS CAFE

Plain English

To get the address of a variable, use:

[a variable]'s whereabouts

Note that this address cannot be modified.

PowerBASIC

'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)

'can't set the address of a single variable, but can access memory locations
DIM z AS INTEGER
z = PEEK(INTEGER, y)

'or can do it one byte at a time
DIM zz(1) AS BYTE
zz(0) = PEEK(BYTE, y)
zz(1) = PEEK(BYTE, y + 1)
'(MAK creates an INTEGER, LONG, or QUAD out of the next smaller type)
z = MAK(INTEGER, zz(0), zz(1))

'*can* set the address of an array
DIM zzz(1) AS BYTE AT y
'zzz(0) = low byte of x, zzz(1) = high byte of x

PureBasic

Get the address of a variable using the '@' operator.

a.i = 5
MessageRequester("Address",Str(@a))


Set the address of a structured pointer. The pointer can be dereferenced to interact with it's data. Ensure that there is access to the memory address that is assigned to the pointer (i.e. part of allocated memory).

a.i = 5
*b.Integer = @a    ;set *b equal to the address of variable a 
*c.Integer = $A100 ;set *c to point at memory location $A100 (in hex)


MessageRequester("Address",Str(*b)) ;display the address being pointed at by *b
MessageRequester("Value",Str(*b\i)) ;de-reference the pointer *b to display the data being pointed at

Python

Python traditionally doesn't support low-level operations on memory addresses, except in the limited sense that one can use the mmap module where it's available, and manipulate offsets into memory map objects...including serializing other objects into and out of the memory mapping. New versions of Python support a ctypes module which permits some low level address operations on C-type objects (see C-types Reference for details).

The Python id() function returns a unique ID for any object. This just happens to be implemented as the base address of the object in C Python[2]; but that is not guaranteed by the semantics of the language and should not be considered a standard, nor used as such. But for comparison purposes the ID can be used as an address, since different extant objects will have different IDs.

foo = object()  # Create (instantiate) an empty object
address = id(foo)

In addition some folks have written binary Python modules which implement "peek" and "poke" operations, but these are non-standard.

Quackery

Quackery does not have variables, and its memory model is based on dynamic arrays ("nests" in Quackery parlance) rather than a single continuous block of RAM, so, for example, an entry on the return stack has two parts; a pointer to a nest and a numerical offset into the nest (i.e. the location of an item within the nest) If the offset is non-negative, the offset is from the (zero-based) start of the nest, and if the offset is negative it is from the end of the nest, with the last item in the nest being at position -1.

The word peek returns a item located within a nest, given a nest and an offset.

The word poke takes a Quackery object, a nest, and an offset as arguments and returns a new nest, similar to the argument nest, except with the contents of the offset location replaced by the specified object. (Nests are immutable except under specific circumstances.)

Illustrating this as a dialogue in the shell (the Quackery REPL.)

/O> [ 10 11 12 13 14 ] is mynest ( create a named nest containing numbers )
... ' mynest 2 peek echo         ( print the content of item #2 in mynest )
... 
12
Stack empty.

/O> 99999 ' mynest 2 poke echo   ( replace 12 with 99999 and print result )
... 
[ 10 11 99999 13 14 ]
Stack empty.

quid returns a numerical value associated with an object in Quackery. See the discussion of id() in the Python entry. Quackery is implemented in Python, and quid in Quackery is equivalent to id() in Python.

QB64

' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions
Type points
    x As Integer
    y As Integer
    z As Integer
End Type

Dim Shared m(3) As _MEM
Dim Shared Saved As points, first As points

m(1) = _Mem(first.x)
m(2) = _Mem(first.y)
m(3) = _Mem(first.z)

print "QB64 way to manage address of variable..."
first.x = 3: first.y = 5: first.z = 8
Print first.x, first.y, first.z
Save first
first.x = 30: first.y = 50: first.z = 80
Print first.x, first.y, first.z

RestoreIt
Print first.x, first.y, first.z

_MemFree m(1)
_MemFree m(2)
_MemFree m(3)
End

Sub Save (F As points)
    Saved.x = F.x
    Saved.y = F.y
    Saved.z = F.z
End Sub

Sub RestoreIt
    _MemPut m(1), m(1).OFFSET, Saved.x
    _MemPut m(2), m(2).OFFSET, Saved.y
    _MemPut m(3), m(3).OFFSET, Saved.z
End Sub
' Full demonstration of being together Qbasic and QB64 methods for accessing and modifying memory directly
Dim A As Integer, B As String, C(1 To 4) As Double

Print " OLD FASHION MODE OF QBASIC / QUICKBASIC"
Sleep 2: Cls
'Print
Print " GETTING ADDRESS OF VARIABLE"
Print "address of variable QuickBasic compatible in 16 bit OS is emulated in QB64"
Print "Qbasic and QuickBasic used as address a Segment and an Offset"
Print "and by cause many QBasic statements change addresses of variables "
Print "for reorganization of RAM it is higly reccomanded to use"
Print "immediately the address of variable got by Varptr and Varseg"
Print "address of A "; VarSeg(A); "-"; VarPtr(A)
Print "address of the first byte of string B "; VarSeg(B); "-"; VarPtr(B)
Print "address of the 2nd element of array C"; VarSeg(C(2)); "-"; VarPtr(C(2))
Print "address of string B from actual data Segment"; SAdd(B)
Print
Print "Direct access to ram video example "
Print " setting Text video ram as Segment": Def Seg = &HB800
Print "reading at offset 240 of text video ram "; Peek(240)
Print "changing at offset 240 of text video ram with"; Asc("@"); " from e to @"
Poke 240, Asc("@")
Print "changing foreground and background color of a character in text video ram "
Poke 241, Peek(241) Xor &B110111
Poke 265, Peek(265) Xor &B010101
Poke 267, Peek(267) Xor &B001010
Def Seg
Print
Print " CREATING VARIABLE AT A SPECIFIC ADDRESS"
Print " created variable D as single at "; VarSeg(d); "-"; VarPtr(d)
Print "Using the variable in normal way"
Print d
d = 100
Print d
Print " press any key to continue..."; Input$(1)
Cls
Print "Only QB64 methods... _MEM functions"
Dim M As _MEM

A = 2: Print "A is "; A
M = _Mem(A) ' it accesses to variable A

_MemPut M, M.OFFSET, 10 As INTEGER ' it modifies value of A
Print " and now A is "; A

Print "d is "; d
d = _MemGet(M, M.OFFSET, Integer) ' it gets value of A into d
Print "and now d is "; d
_MemFree M
End

R

With the library pryr

x <- 5
y <- x
pryr::address(x)
pryr::address(y)

y <- y + 1

pryr::address(x)
pryr::address(y)

Without any libraries

address <- function(obj) { 
  paste0("0x", substring(sub(" .*$","",capture.output(.Internal(inspect(obj)))),2))
}

x <- 5
y <- x
address(x)
address(y)

y <- y + 1
address(x)
address(y)
Output:
[1] "0xbc60668"
[1] "0xbc60668"
[1] "0xbc60668"
[1] "0xbcc1680"

Racket

#lang racket

(require ffi/unsafe)

(define (madness v) ; i'm so sorry
   (cast v _racket _gcpointer))

To test that it is doing "sane" things, you can retrieve the value of the C short located at the pointer produced. Racket objects start with a 2-byte tag indicating their type. These calls should all produce fairly small numbers: the Racket source I'm looking at uses only the first 259 tag values. Small fixnums are stored directly in tagged pointers, so attempting this dereferencing on the pointer madness gives you from a fixnum will most likely segfault your process.

(ptr-ref (madness +) _short)
(ptr-ref (madness (/ 4 3)) _short)
(ptr-ref (madness 3.2) _short)
(ptr-ref (madness (sqrt -2)) _short)
(ptr-ref (madness #\a) _short)
(ptr-ref (madness 'foo) _short)

Raku

(formerly Perl 6)

my $x;
say $x.WHERE;

my $y := $x;   # alias
say $y.WHERE;  # same address as $x

say "Same variable" if $y =:= $x;
$x = 42;
say $y;  # 42
Output:
7857931379550584425

How you set the address of a variable (or any other object) is outside the purview of Raku, but the language supports pluggable object representations, and any given representation scheme could conceivably allow an existing address to be treated as an object candidate where that makes sense. Memory-mapped structs are not unreasonable and are likely to be supported on VMs that allow it.

RapidQ

Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
    MyVar = 10

'Get the address of MyVar
TheAddress = varptr(MyVar)

'Set a new value on the address
MEMSET(TheAddress, 102, SizeOf(byte))

'Myvar is now = 102
showmessage "MyVar = " + str$(MyVar)

'...or copy from one address to another using:
MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))

'SecVar is now also = 102
showmessage "SecVar = " + str$(SecVar)

Retro

Retro is only able to directly access memory as 32-bit values within a linear address space.

Get The Address

'a var
&a

Set The Address

Create variable b and point it to address 100

'b var
#100 @Dictionary d:xt store

Byte Addressing

Retro includes a standard library allowing for creation and access of byte-level data. This is done using words which mask, unpack, and repack the bytes within the 32-bit cells.

To read the value at byte address 100:

'example/ByteAddressing.forth include
#100 b:fetch

Or to alter the value at byte address 100:

$e #100 b:store

REXX

REXX has no easy way of getting the address of variables within the langage itself, but since each
REXX variable can be accessed by name and its name passed to (say) subroutines [PROCEDUREs],
with the use of the VALUE and SYMBOL built-in functions (BIFs), it's possible to determine
the state of any variable (defined or not defined, its value, length of the variable's value).

It is possible to use the BIF (shown below)  (at least, in the original REXX)

zzz = storage(xxx)

(but only in some REXX interpreters)   to access the internal REXX pool of variables, but it
would depend on the (internal) REXX internal structure(s) and almost likely be not portable nor
useable across releases of REXX or the operating system.   It would be necessary to follow a
pretty complex chain of pointers to just find the REXX pool of variables and the internal structure
may be pretty complicated and somewhat obscure.   Going down this path is not for the faint of
heart.

Ruby

You can't access the address of a "variable" in Ruby. However, it may be possible to get the address of an object.

The Ruby object_id method returns an object ID that is unique among active objects. It turns out that for the official Ruby implementation, the object ID is based on the address. For non-immediate objects (i.e. anything other than a Fixnum, Symbol, true, false, or nil), the address can be obtained by shifting the object ID one to the left. For more information, see the source code for the object_id method:[3].

For classes that do not override the to_s method, the to_s method also shows the address.

>foo = Object.new  # => #<Object:0x10ae32000>
>id = foo.object_id  # => 2238812160
>"%x" % (id << 1)  # => "10ae32000"

Rust

It is not possible to change the memory address of an existing variable in Rust directly. However, you could make a copy of the value and then write it to a specific address.

let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
let mut v2;
// Override rust protections on reading from uninitialized memory
unsafe {v2 = mem::uninitialized();} 
let addr = &mut v2 as *mut _;

// ptr::write() though it takes v1 by value, v1s destructor is not run when it goes out of
// scope, which is good since then we'd have a vector of free'd vectors
unsafe {ptr::write(addr, v1)}
println!("New address: {:p}", &v2);

Get the memory address of a variable:

let var = 1;
println!("address of var: {:p}", &var);

Get the value at a certain memory address:

let address: usize = 0x7ffc8f303130;
unsafe {
    let val = *(address as *const usize);
    println!("value at {}: {:?}", address, val);
}

Set the value at a certain memory address:

unsafe {
    *(0x7ffc8f303130 as *mut usize) = 1;
    // Note that this invokes undefined behavior if 0x7ffc8f303130 is uninitialized. In that case, std::ptr::write should be used.
    std::ptr::write(0x7ffc8f303130 as *mut usize, 1);
}

Scala

There is no way to access addresses in Scala. It's governed by the Memory Management of the JVM controlling or knowing the addresses makes absolutely no sense in Scala.

Sidef

var n = 42;
say Sys.refaddr(\n);        # prints the address of the variable
say Sys.refaddr(n);         # prints the address of the object at which the variable points to
Output:
42823224
37867184

Smalltalk

This task does not really make sense in Smalltalk: for one, all we could ask for is the address of an object, not a variable, which is a binding of a name to a value in a lexical scoping (similar to Scheme, Common Lisp and other managed languages). Second, the underlying memory management (garbage collector) is usually free to move objects around, and most implementations do so when objects are tenured or memory areas are defragmented (also similar). So its usefulness is limited to VM developers and debuggers ;-)

You asked for it, and here it is:

Works with: Smalltalk/X
|p|
p := Point x:10 y:20.
ObjectMemory addressOf:p.
ObjectMemory collectGarbage.
ObjectMemory addressOf:p "may return another value"

to deal with non-Smalltalk objects, all Smalltalks provide libraries to pass-in and out parameters to foreign function calls (FFI). The underlying memory block will not be moved by the garbage collector and the address can be passed to external (eg. C, C++, asm) functions. For those, we can allocate a block of memory and fiddle around with its "address":

Works with: Smalltalk/X
|ptr|
ptr := ExternalBytes new:10.
ptr address.
ptr byteAt:1 put: 16rFF.

However, there are "reference holders", similar to box-objects in scheme/lisp. In Smalltalk these are called "ValueHolder" and are heavily used in UI frameworks. Usually, they are used with the observer pattern as shown in the following example:

|holder|
holder := ValueHolder with:123.
holder onChangeSend:#someChange to:someone.
holder value: 234


Stata

See pointers in Stata help. It's not possible to set the address of a variable, but on can get the address of a variable or a function with the & operator.

a = 1
&a

function f(x) {
	return(x+1)
}

&f()

Swift

class MyClass { }

func printAddress<T>(of pointer: UnsafePointer<T>) {
    print(pointer)
}

func test() {
    var x = 42
    var y = 3.14
    var z = "foo"
    var obj = MyClass()

    // Use a pointer to a variable on the stack and print its address.
    withUnsafePointer(to: &x)   { print($0) }
    withUnsafePointer(to: &y)   { print($0) }
    withUnsafePointer(to: &z)   { print($0) }
    withUnsafePointer(to: &obj) { print($0) }

    // Alternately:
    printAddress(of: &x)
    printAddress(of: &y)
    printAddress(of: &z)
    printAddress(of: &obj)

    // Printing the address of an object that an object reference points to.
    print(Unmanaged.passUnretained(obj).toOpaque())
}

test()
Output:
0x00007fffe61bcac0
0x00007fffe61bcab8
0x00007fffe61bcaa0
0x00007fffe61bca98
0x00007fffe61bcac0
0x00007fffe61bcab8
0x00007fffe61bcaa0
0x00007fffe61bca98
0x000000000082e2f0

Tcl

It is highly unusual to want to directly manipulate the address of a variable in Tcl, as it is a thoroughly unsafe operation. Indeed, Tcl does not expose any mechanism to do so at the script level. However, Tcl does contain a C-level API function, Tcl_LinkVar, to arrange for a variable's value to always reflect the contents of a particular address in memory. (See Machine Address for an example of how to do that.)

However, that's not the only way of doing it. You can also use the critcl library to put C code directly inside a Tcl script and so work with addresses directly that way.

Library: critcl
package require critcl
# This code assumes an ILP32 architecture, like classic x86 or VAX.
critcl::cproc peek {int addr} int {
    union {
       int i;
       int *a;
    } u;

    u.i = addr;
    return *u.a;
}
critcl::cproc poke {int addr int value} void {
    union {
        int i;
        int *a;
    } u;

    u.i = addr;
    *u.a = value;
}
package provide poker 1.0

Demonstrating:

package require poker

# Increment a memory location; this will probably crash if you try for real.
# We don't define how to get a good address, but it's not usually a problem
# for embedded programming...
set where 0x12340
poke $where [expr {[peek $where] + 1}]

Have great care with this sort of code; the damage you can do by writing to random locations is considerable and being able to read from anywhere could allow information to flow to otherwise unauthorized programs.

Toka

Get the Address

The default behaviour of a data element in Toka is to return its address. This makes obtaining the address trivial:

variable foo
foo .

Set the Address

You can manually assign a name to any memory address (or other number), but you should make sure it's part of allocated memory first.

 hex abcdef is-data foo
 foo .


VBA

The VarPtr function allows one to get the address of a variable. There are also functions to peek/poke values at a given address.

Option Explicit
Declare Sub GetMem1 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Byte)
Declare Sub GetMem2 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Integer)
Declare Sub GetMem4 Lib "msvbvm60" (ByVal ptr As Long, ByRef x As Long)
Declare Sub PutMem1 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Byte)
Declare Sub PutMem2 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Integer)
Declare Sub PutMem4 Lib "msvbvm60" (ByVal ptr As Long, ByVal x As Long)

Sub Test()
    Dim a As Long, ptr As Long, s As Long
    a = 12345678
    
    'Get and print address
    ptr = VarPtr(a)
    Debug.Print ptr
    
    'Peek
    Call GetMem4(ptr, s)
    Debug.Print s
    
    'Poke
    Call PutMem4(ptr, 87654321)
    Debug.Print a
End Sub

Visual Basic .NET

Visual Basic uses managed memory that can be moved around at any time. If a memory address for a variable is needed, the address is created first and then its contents copied.

Get the Address

Allocates a stable address in unmanaged memory, copies a variable to it, then returns the address itself.

 Dim x = 5
 Dim ptrX As IntPtr
 ptrX = Marshal.AllocHGlobal(Marshal.SizeOf(GetType(Integer)))
 Marshal.StructureToPtr(5, ptrX, False)
 Dim addressX = ptrX.ToInt64

Set the Address

Sets the pointer to the address A100 in hex.

 Dim ptrX As New IntPtr(&HA100)

V (Vlang)

fn main() {
	var := 42
	address_of_var := &var // pointer to variable
	println(&address_of_var) // reference
	println(*address_of_var) // dereference a reference // 42
}

Wart

addr.x
=> 27975840

addr is guaranteed to provide a stable identifier for this session. The address is just a number like any other and you can perform all the arithmetic you like on it. However, there's no way to dereference an address back into a value, so this is not pointer arithmetic. The primary use of addr is to check if two objects are the same and not just copies, like Common Lisp's eq operator.

if (addr.x = addr.y)
  ..

As a result, Wart has only one way to compare values: by default two objects are considered equal if they are structurally isomorphic. (You can override it if you want a different behavior.)

Wren

In Wren, with the exception of the built-in types Num, Bool and Null which hold their values directly, variables always contain an 8 byte pointer to where their actual data is stored on the heap.

However, there is no way to get or set the address of a variable and, since memory management is completely automatic, it is difficult to think of circumstances where this would be useful.

You can, of course, assign a variable of one reference type to another which under the hood copies the pointer so that both variables access the same data store.

var a = [1, 2, 3, 4]
var b = a // now 'a' and 'b' both point to the same List data
b[3] = 5
System.print("'b' is %(b)")
System.print("'a' is %(a)") // the previous change is of course reflected in 'a' as well
var t = Object.same(a, b)   // tells you whether 'a' and 'b' refer to the same object in memory 
System.print("'a' and 'b' are the same object? %(t ? "yes" : "no")")
Output:
'b' is [1, 2, 3, 5]
'a' is [1, 2, 3, 5]
'a' and 'b' are the same object? yes

X86 Assembly

For SVR4 Unix-like style assembler the address of a variable is its symbol. (On some systems the names of C language variables have an extra leading underscore.)

        movl    my_variable, %eax

For SVR4 style code destined for a shared library it's necessary to fetch the address from the global offset table to ensure position independent code. That table is found relative to the program counter using the special _GLOBAL_OFFSET_TABLE_ (or on some systems extra leading underscore __GLOBAL_OFFSET_TABLE_). The C compiler normally does this in %ebx but for hand-crafted assembler anything equivalent is possible.

        call    eip_to_eax
        addl    $_GLOBAL_OFFSET_TABLE_, %eax
        movl    my_variable@GOT(%eax), %eax
        ...
eip_to_eax:
        movl    (%esp), %eax
        ret

XLISP

To get the address in the heap of a variable X, use:

(%ADDRESS-OF X)

If by "setting the address" we mean compelling the system to store a variable at a particular address of our choosing, then there is no easy way to do that.

XPL0

It is easy to get the address of a variable (relative to the beginning of its data segment), but there is no way to set the address of a variable. However, pointers can be used to access specific addresses. The example shows how the pointer B(0) is used to access the variable A and set it to hex 1234ABCD. The Peek and Poke intrinsics can be used to access specific hardware addresses. The absolute hardware address of a program's data segment can be obtained using the GetReg intrinsic. The '@' operator works exactly like 'addr' for integers but returns a 'real' pointer, instead of a 32-bit relative address, when used on a 'real' variable.

include c:\cxpl\codes;
int  A, B;
[B:= addr A;
HexOut(0, B);  CrLf(0);
B(0):= $1234ABCD;
HexOut(0, A);  CrLf(0);
]
Output:
00000F48
1234ABCD

Yorick

Yorick has pointers, but they are typically used in an opaque fashion. Pointer arithmetic is not supported, not is referencing arbitrary memory locations. However, a pointer address may be copied to other variables. Here is an interactive example that illustrates some of this.

> foo = 1
> bar = &foo
> bar
0x15f42c18
> baz = bar
> *baz = 5
> *bar
5
> *baz
5

Z80 Assembly

A variable's address is known in advance if the programmer is writing the assembly code themselves. In order to load from a variable, the address must be specified as an operand. So "getting the address" doesn't really apply to Z80 Assembly.

Setting an address is just storing a register into memory. There are several ways to do this:

Specifying a Memory Location

Only the accumulator A can do this. If you want to store another 8-bit register's contents directly into memory, you'll need to load that register's contents into A first:

foo equ &C000
bar equ &C001
ld (foo),a  ;store A into memory location &C000
ld a,b      ;copy B to A
ld (bar),a  ;store "B" into memory location &C001

Using BC or DE

Only the accumulator A can do this. If you want to store another 8-bit register's contents into the address pointed to by BC or DE, you'll need to load that register's contents into A first:

foo equ &C000
bar equ &C001

ld bc,foo ;notice the lack of parentheses here. This is important.
ld (bc),a

ld de,bar
ld (de),a

Using HL

The 8-bit registers A,B,C,D,E can all do this. H and L cannot, unless the value being stored happens to equal that "half" of the memory location.

foo equ &C000
bar equ &C001
ld hl,foo
ld (hl),b  ;store the contents of B into foo

;since bar just happens to equal foo+1, we can do this:

inc hl
ld (hl),c  ;store the contents of C into bar

16-Bit Values into A Specified Memory Location

Storing a 16-Bit value is a little more complicated. The registers BC,DE,HL,IX,IY,SP can all do this, with a specified memory location. The "low byte" of the register (C, E, L, IXL, IYL, and the low byte of SP) are stored at the memory location specified in parentheses, and the "high byte" of the register (B, D, H, IXH, IYH, and the high byte of SP) are stored in the memory location after that. The Game Boy/Sharp LR35902 can only do this with SP, and no other registers.

foo equ &C000
bar equ &C001

ld (foo),bc  ;store C into "foo" and B into "bar"

Beware! In this example, the second instruction clobbers part of the first. It's important to be careful when storing 16-bit values into memory.

foo equ &C000
bar equ &C001

ld (foo),de  ;store E into &C000 and D into &C001
ld (bar),bc  ;store C into &C001 and B into &C002

Zig

Works with: Zig version 0.11.0
const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    var i: i32 = undefined;
    var address_of_i: *i32 = &i;

    try stdout.print("{x}\n", .{@intFromPtr(address_of_i)});
}