Address of a variable: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
(27 intermediate revisions by 16 users not shown)
Line 9:
===Get the Address===
To get the address of a variable, use <code>LA</code> (load address) instead of <code>L</code> (load):
<langsyntaxhighlight lang="360asm"> LA R3,I load address of I
...
I DS F</langsyntaxhighlight>
 
===Set the Address===
To set a variable dynamically at the same address of an other variable, use a <code>DSECT</code> (dummy section):
<langsyntaxhighlight lang="360asm"> USING MYDSECT,R12
LA R12,I set @J=@I
L R2,J now J is at the same location as I
Line 21:
I DS F
MYDSECT DSECT
J DS F</langsyntaxhighlight>
=={{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.
 
<langsyntaxhighlight lang="6502asm">;;;;;;; zero page RAM memory addresses
CursorX equ $00
CursorY equ $01
Line 33:
 
Joystick1 equ $DC01
Joystick2 equ $DC00</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="6502asm">LDA #$20 ; load a constant into the accumulator
 
CLC
Line 45:
 
STA temp ; store the result in a temp variable (really a zero-page memory address).
</syntaxhighlight>
</lang>
 
6502 assemblers treat a number without a # in front as a memory address.
<langsyntaxhighlight 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.</langsyntaxhighlight>
 
The only exception to this rule is when defining bytes. These do not have # in front, but are treated as constants nonetheless:
<langsyntaxhighlight lang="6502asm">byte $30,$20,$10,$00 ;these are constant numeric values, not memory addresses.</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="68000devpac">UserRam equ $100000
Cursor_X equ UserRam ;$100000, byte length
Cursor_Y equ UserRam+1 ;$100001, byte length
Line 65:
;GET THE ADDRESS
 
LEA ThirtyTwoBitData,A0 ;load $100004 into A0.</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="68000devpac">MOVE.L #$11223344,D0
MOVE.L D0,(A0) ; store D0 into ThirtyTwoBitData ($100004)
; HEXDUMP OF $100004:
Line 75:
; $100005: $22
; $100006: $33
; $100007: $44</langsyntaxhighlight>
 
 
Line 83:
{{works with|https://www.dosbox.com DOSBox}}
===Get The Address===
<langsyntaxhighlight lang="asm">.model small
.stack 1024
.data
Line 94:
 
mov ax, offset UserRam ;load into AX the address of UserRam
mov di, ax ;load that value into the destination index register</langsyntaxhighlight>
 
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.
Line 101:
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.
 
<langsyntaxhighlight lang="asm">mov ax, 0FFFFh
mov [es:di],ax ;store 0xFFFF into the base address of UserRam.</langsyntaxhighlight>
 
Alternatively, this would also work:
<langsyntaxhighlight lang="asm">.model small
.stack 1024
.data
Line 117:
 
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.</langsyntaxhighlight>
 
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AArch64 Raspberry PI 3B */
/* program adrvar.s */
Line 197:
ret // retour adresse lr x30
 
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
BYTE v=[123]
 
PrintF("Value of variable: %B%E",v)
PrintF("Address of variable: %H%E",@v)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Address_of_a_variable.png Screenshot from Atari 8-bit computer]
Line 215:
=={{header|Ada}}==
===Get The Address===
<langsyntaxhighlight lang="ada">The_Address : System.Address;
I : Integer;
The_Address := I'Address;</langsyntaxhighlight>
===Set The Address===
Set the address of a variable to address A100 in hexadecimal
<langsyntaxhighlight lang="ada">I : Integer;
for I'Address use 16#A100#;</langsyntaxhighlight>
Set the address of one variable to the address of another variable, creating an overlay.
<langsyntaxhighlight lang="ada">I : Integer;
J : Integer;
for I'Address use J'Address;</langsyntaxhighlight>
{{omit from|Lua}}
 
=={{header|ALGOL 68}}==
Line 234 ⟶ 233:
But the value of the actual address is not available
for printing or any arithmetic.
<langsyntaxhighlight lang="algol68">[4]INT test := (222,444,666,888);
REF INT reference := test[3];
REF INT(reference) := reference + 111;
print(("test value is now: ",test))</langsyntaxhighlight>
{{out}}
<pre>test value is now: +222 +444 +777 +888</pre>
Line 251 ⟶ 250:
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:<langsyntaxhighlight lang="algol68">PROC establish = (REF FILE file, STRING idf, CHANNEL chan, INT p, l, c) INT: ~</langsyntaxhighlight>
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
Line 263 ⟶ 262:
=== Get the address ===
Get the address of the last variable used.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">N = N : PRINT PEEK (131) + PEEK (132) * 256</langsyntaxhighlight>
Get (find) the address of a function.
<langsyntaxhighlight ApplesoftBasiclang="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"
2 IF A THEN PRINT A
</syntaxhighlight>
</lang>
 
=== Set the address ===
Set the address where variables are stored, but clears all variables.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">LOMEM: 4096
I% = I% : PRINT PEEK (131) + PEEK (132) * 256
</syntaxhighlight>
</lang>
Set the address and length of a string.
<langsyntaxhighlight ApplesoftBasiclang="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
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
</syntaxhighlight>
</lang>
Set the address of a function.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">0 DEF FN F(X) = 1
1 DEF FN B(X) = 2
2 N$ = "F" : GOSUB 8 : FA = A
Line 292 ⟶ 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
9 NEXT A : PRINT "FN " N$ " NOT FOUND"
</syntaxhighlight>
</lang>
 
=={{header|Argile}}==
=== Get the address ===
{{works with|Argile|1.0.0}}
<langsyntaxhighlight Argilelang="argile">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 :)</langsyntaxhighlight>
=== Set the address ===
Since we cannot set address of a variable, we use a macro
that returns a reference.
{{works with|Argile|1.0.0}}
<langsyntaxhighlight Argilelang="argile">use std, array
=:mac:= -> int& { * (0x400000 as int*) }
printf "%x\n" mac (: may crash depending on operating system :)
</syntaxhighlight>
</lang>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 385 ⟶ 384:
bx lr /* retour procedure */
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">x: 2
xInfo: info.get 'x
 
Line 395 ⟶ 394:
"address of x:" xInfo\address
"->" from.hex xInfo\address
]</langsyntaxhighlight>
 
{{out}}
Line 402 ⟶ 401:
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">var num = 12
var pointer = ptr(num) # get pointer
 
Line 409 ⟶ 408:
@unsafe # bad idea!
pointer.addr = 0xFFFE # set the address
</syntaxhighlight>
</lang>
 
=={{header|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
<syntaxhighlight lang AutoHotkey="autohotkey">msgbox % &var</langsyntaxhighlight>
 
=={{header|Axe}}==
 
Axe supports getting the address of a variable using the degree symbol:
<langsyntaxhighlight lang="axe">°A→B
.B now contains the address of A</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="axe">1234→A
1→{A}</langsyntaxhighlight>
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}}==
 
<langsyntaxhighlight lang="freebasic">
'---get a variable's address
LOCAL x TYPE long
PRINT ADDRESS(x)
</syntaxhighlight>
</lang>
 
=={{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).
<langsyntaxhighlight lang="qbasic">'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
Line 444 ⟶ 443:
DIM z AS INTEGER
z = PEEK(y)
z = z + (PEEK(y) * 256)</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
The original BBC BASIC doesn't provide an address-of operator, but ''BBC BASIC for Windows'' does:
<langsyntaxhighlight lang="bbcbasic">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%</langsyntaxhighlight>
 
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++}}==
Line 461 ⟶ 472:
=== 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>.
<langsyntaxhighlight lang="cpp">int i;
void* address_of_i = &i;</langsyntaxhighlight>
 
'''C++ only:''' C++ allows overloading the <code>&</code> operator. To bypass this, for example in generic code, use the library function <code>addressof</code>:
 
<langsyntaxhighlight lang="cpp">#include <memory>
int i;
auto address_of_i = std::addressof(i);</langsyntaxhighlight>
 
=== 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:
<langsyntaxhighlight lang="cpp">int& i = *(int*)0xA100;</langsyntaxhighlight>
 
If the type of the variable requires initialization, it is necessary to use placement new:
<langsyntaxhighlight lang="cpp">#include <new>
struct S { int i = 0; S() {} };
auto& s = *new (reinterpret_cast<void*>(0xa100)) S;</langsyntaxhighlight>
 
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):
<langsyntaxhighlight lang="cpp">static union
{
int i;
int j;
};</langsyntaxhighlight>
'''C++ only:''' An alternative (and cleaner) solution is to use references:
<langsyntaxhighlight lang="cpp">int i;
int& j = i;</langsyntaxhighlight>
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>:
 
<langsyntaxhighlight lang="cpp">#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);</langsyntaxhighlight>
 
{{omit from|Clojure}}
 
=={{header|C sharp|C#}}==
Line 506 ⟶ 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*.
 
<langsyntaxhighlight lang="csharp">unsafe
{
int i = 5;
void* address_of_i = &i;
}</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 516 ⟶ 526:
 
===Get Address===
<syntaxhighlight lang="cobol"> DATA DIVISION.
<lang cobol>data division.
WORKING-STORAGE SECTION.
working-storage section.
01 ptr usageUSAGE pointerPOINTER.
01 var picPIC xX(64).
 
PROCEDURE DIVISION.
procedure division.
set SET ptr toTO addressADDRESS ofOF var.</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="cobol">
OCOBOL*> Rosetta Code set address example
*> tectonics: cobc -x setaddr.cob && ./setaddr
program-id.IDENTIFICATION setaddrDIVISION.
dataPROGRAM-ID. divisionsetaddr.
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.
set01 var address of var to addressPIC ofX(8) preallocBASED.
display var end-display
gobackPROCEDURE 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}}==
Line 548 ⟶ 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:
 
<langsyntaxhighlight lang="lisp">;;; 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)
Line 563 ⟶ 615:
 
;; *y* -> 42
;; *x* -> 0</langsyntaxhighlight>
 
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 579 ⟶ 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.
 
<langsyntaxhighlight lang="lisp">(use-package :ffi)
 
(defmacro def-libc-call-out (name &rest args)
Line 605 ⟶ 657:
(defsetf get-errno set-errno)
 
(define-symbol-macro errno (get-errno)))</langsyntaxhighlight>
 
Test:
Line 618 ⟶ 670:
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE AddressVar;
IMPORT SYSTEM,StdLog;
Line 633 ⟶ 685:
x := 10;
END AddressVar.
</syntaxhighlight>
</lang>
Execute: ^Q AddressVar.Do<br/>
{{out}}
Line 641 ⟶ 693:
 
=={{header|Creative Basic}}==
<syntaxhighlight lang="creative basic">
<lang Creative Basic>
== Get ==
 
Line 714 ⟶ 766:
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem
</syntaxhighlight>
</lang>
 
=={{header|D}}==
 
Take the address of a variable:
<langsyntaxhighlight lang="d">int i;
int* ip = &i;</langsyntaxhighlight>
 
Using a numeric value:
<langsyntaxhighlight lang="d">int* ip = cast(int*)0xdeadf00d;</langsyntaxhighlight>
 
Locating a "regular" variable at a specific address is not possible.
Line 729 ⟶ 781:
The closest thing is passing a dereferenced pointer to a reference parameter.
 
<langsyntaxhighlight lang="d">void test(ref int i) {
import std.stdio;
writeln(&i);
Line 736 ⟶ 788:
void main() {
test(* (cast(int*)0xdeadf00d) );
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 743 ⟶ 795:
 
To get the address of any variable, structure, procedure or function use the <tt>@</tt>-operator:
<langsyntaxhighlight lang="pascal">var
i: integer;
p: ^integer;
Line 749 ⟶ 801:
p := @i;
writeLn(p^);
end;</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="pascal">var
crtMode: integer absolute $0040;
str: string[100];
strLen: byte absolute str;
</syntaxhighlight>
</lang>
 
=={{header|Draco}}==
<langsyntaxhighlight 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:
Line 787 ⟶ 839:
writeln("var2 address=", pretend(&var2,word):5, " value=", var2:5);
writeln("memtop2 address=", pretend(&memtop2,word):5, " value=", memtop2:5)
corp</langsyntaxhighlight>
{{out}}
<pre>var address= 276 value= 1234
Line 796 ⟶ 848:
=={{header|ERRE}}==
ERRE hasn't explicit pointers, but only a function that gets the address of a variable
<syntaxhighlight lang="text">
........
A%=100
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.
Using this address you can modify the variable's value without using an assignment statement:
<syntaxhighlight lang="text">
PROGRAM POINTER
BEGIN
Line 813 ⟶ 865:
PRINT(A%) ! prints 200
END PROGRAM
</syntaxhighlight>
</lang>
Note: With C-64 substitute POKE(ADDR,200) with POKE(ADDR+3,200).
 
Line 869 ⟶ 921:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program test_loc
implicit none
 
Line 877 ⟶ 929:
i = loc(r)
print *, i
end program</langsyntaxhighlight>
Note: <code>loc</code> is a common extension that is implemented
by e.g. the Intel Fortran Compiler, G95 and gfortran.
Line 883 ⟶ 935:
=={{header|FreeBASIC}}==
One can get the address of a variable using the @ operator:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
Dim a As Integer = 3
Dim p As Integer Ptr = @a
Print a, p </langsyntaxhighlight>
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:
<langsyntaxhighlight lang="freebasic">Var p = Cast(Integer Ptr, 1375832)
*p = 42
Print p, *p</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">window 1
include "ConsoleWindow"
 
dim as short i : i = 575
dim as ptr j : j = NULL
 
j = @i
 
printprintf @"AdddressAddress of i ="; %ld",j
print @"Value of i = ";peek [word(j])
 
</lang>
HandleEvents</syntaxhighlight>
 
Output:
<pre>
Adddress of i = 9021644330713552
Value of i = 575
</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}}==
Line 928 ⟶ 1,016:
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.
<langsyntaxhighlight lang="go">package main
 
import (
Line 959 ⟶ 1,047:
i := (*int32)(unsafe.Pointer(&myVar))
fmt.Printf("value as int32: %#08x\n", *i)
}</langsyntaxhighlight>
{{out}}
On a 32 bit architecture:
Line 978 ⟶ 1,066:
 
=={{header|IWBASIC}}==
<syntaxhighlight lang="iwbasic">
<lang IWBASIC>
== Get ==
 
Line 1,008 ⟶ 1,096:
#<UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT
DELETE pMem
</syntaxhighlight>
</lang>
 
=={{header|J}}==
Line 1,014 ⟶ 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:
 
<syntaxhighlight lang="text"> 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</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,028 ⟶ 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.
 
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>: <langsyntaxhighlight lang="julia">julia> x = [1, 2, 3]
julia> ptr = pointer_from_objref(x)
Ptr{Void} @0x000000010282e4a0
Line 1,035 ⟶ 1,123:
1
2
3</langsyntaxhighlight> 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:<langsyntaxhighlight lang="julia">julia> A = [1, 2.3, 4]
3-element Array{Float64,1}:
1.0
Line 1,060 ⟶ 1,148:
1.0
2.3
3.14149</langsyntaxhighlight>
 
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>:<langsyntaxhighlight lang="julia">julia>
julia> q = convert(Ptr{Float64}, 0x0000000113f70d68)
Ptr{Float64} @0x0000000113f70d68
Line 1,069 ⟶ 1,157:
2-element Array{Float64,1}:
2.3
3.14149</langsyntaxhighlight>
 
{{omit from|K}}
 
=={{header|Kotlin}}==
Line 1,078 ⟶ 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.
{{works with|Ubuntu|14.04}}
<langsyntaxhighlight lang="scala">// Kotlin Native v0.5
 
import kotlinx.cinterop.*
Line 1,087 ⟶ 1,174:
with(intVar) { println("Value is $value, address is $rawPtr") }
nativeHeap.free(intVar)
}</langsyntaxhighlight>
 
{{out}}
Line 1,099 ⟶ 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:
 
<syntaxhighlight lang="scheme">
<lang Scheme>
 
1) lambdas
Line 1,124 ⟶ 1,211:
-> _QUOT_124 // as replaced and protected before 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}}==
 
To obtain the address of any expression in Maple, use the builtin function <code>addressof</code>.
<langsyntaxhighlight Maplelang="maple">> addressof( x );
18446884674469911422</langsyntaxhighlight>The inverse operation is <code>pointto</code>:<langsyntaxhighlight Maplelang="maple">
> pointto( 18446884674469911422 );
x</langsyntaxhighlight>This works for any expression, not just variables:<langsyntaxhighlight Maplelang="maple">> addressof( sin( x )^2 + cos( x )^2 );
18446884674469972158
 
> pointto( 18446884674469972158 );
2 2
sin(x) + cos(x)</langsyntaxhighlight>
 
=={{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}}==
===Get Address===
<langsyntaxhighlight lang="modula2">MODULE GetAddress;
 
FROM SYSTEM IMPORT ADR;
Line 1,152 ⟶ 1,308:
WriteInt(adr, 0);
WriteLn;
END GetAddress.</langsyntaxhighlight>
 
===Set Address===
<langsyntaxhighlight lang="modula2">MODULE SetAddress;
 
CONST adress = 134664460;
Line 1,163 ⟶ 1,319:
BEGIN
(*do nothing*)
END SetAddress.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
===Get Address===
<langsyntaxhighlight lang="nanoquery">import native
 
a = 5
 
println format("0x%08x", native.address(a))</langsyntaxhighlight>
{{out}}
<pre>0xc46be580</pre>
Line 1,177 ⟶ 1,333:
===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.
<langsyntaxhighlight lang="nanoquery">import native
 
a = 123
Line 1,186 ⟶ 1,342:
 
ptr = native.address(b)
println native.object(ptr)</langsyntaxhighlight>
{{out}}
<pre>123
Line 1,193 ⟶ 1,349:
=={{header|NewLISP}}==
===Get Address===
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(set 'a '(1 2 3))
(address a)
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
===Get Address===
<syntaxhighlight lang="oberon2">
<pre>
VAR a: LONGINT;
VAR b: INTEGER;
Line 1,212 ⟶ 1,368:
b := 10;
a := SYSTEM.ADR(b); (* Sets variable a to the address of variable b *)
</syntaxhighlight>
</pre>
 
===Set Address===
<syntaxhighlight lang="oberon2">
<pre>
SYSTEM.PUT(a, b); (* Sets the address of b to the address of a *)
</syntaxhighlight>
</pre>
 
=={{header|OCaml}}==
Line 1,229 ⟶ 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:
 
<langsyntaxhighlight lang="ocaml">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 *)
Line 1,241 ⟶ 1,397:
Printf.printf "%nx\n" (address_of b);;
let c = 17 in
Printf.printf "%nx\n" (address_of c);; (* error, because int is unboxed *)</langsyntaxhighlight>
 
=={{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}}==
Line 1,251 ⟶ 1,419:
For instance, here, after creating and setting a variable A, we store the corresponding word into a variable B :
 
<langsyntaxhighlight Oforthlang="oforth">tvar: A
10 to A
 
Line 1,264 ⟶ 1,432:
[1] (Integer) 12
[2] (Variable) #A
>ok</langsyntaxhighlight>
 
=={{header|Ol}}==
Line 1,292 ⟶ 1,460:
 
=={{header|Panoramic}}==
<syntaxhighlight lang="panoramic">
<lang Panoramic>
== Get ==
 
Line 1,336 ⟶ 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
255 will cause an error.
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
In GP you can sent the address to built-in commands like issquare
<syntaxhighlight lang ="parigp">issquare(n, &m)</langsyntaxhighlight>
but you cannot directly compute with it. You can view the address of a variable and other debugging information with the
<pre>\x</pre>
Line 1,352 ⟶ 1,520:
=={{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.
<langsyntaxhighlight lang="perl">use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; # 140502490125712</langsyntaxhighlight>
Alternatively, the address (in hexadecimal) can be directly obtained with <code>printf</code>:
<langsyntaxhighlight lang="perl">printf "%p", $v; # 7fc949039590</langsyntaxhighlight>
Use Devel::Pointer::PP if you want to dereference a certain address in memory.
 
Line 1,361 ⟶ 1,529:
 
Simple reference (address) manipulation.
<langsyntaxhighlight lang="perl">my $a = 12;
my $b = \$a; # get reference
$$b = $$b + 30; # access referenced value
print $a; # prints 42</langsyntaxhighlight>
 
Example how to make variable overlay.
<langsyntaxhighlight lang="perl">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</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 1,388 ⟶ 1,556:
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.
<!--<langsyntaxhighlight Phixlang="phix">-->
<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>
Line 1,413 ⟶ 1,581:
<span style="color: #000000;">address</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,427 ⟶ 1,595:
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.
<langsyntaxhighlight PicoLisplang="picolisp">: (setq X 7)
-> 7
 
Line 1,440 ⟶ 1,608:
 
: X
-> (a b c)</langsyntaxhighlight>
 
=={{header|PL/I}}==
 
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare addr builtin; /* retrieve address of a variable */
declare ptradd builtin; /* pointer addition */
Line 1,478 ⟶ 1,646:
end;
end;
</syntaxhighlight>
</lang>
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="pli">100H:
/* THERE IS NO STANDARD LIBRARY
THIS DEFINES SOME BASIC I/O USING CP/M */
Line 1,559 ⟶ 1,727:
OF THE STRINGS IN THE 'PRINT' CALLS */
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>FOO IS 0F00 AND ITS ADDRESS IS 03FA
Line 1,567 ⟶ 1,735:
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}}==
<langsyntaxhighlight lang="powerbasic">'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
Line 1,586 ⟶ 1,759:
'*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</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Get the address of a variable using the '@' operator.
<langsyntaxhighlight PureBasiclang="purebasic">a.i = 5
MessageRequester("Address",Str(@a))</langsyntaxhighlight>
 
 
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).
<langsyntaxhighlight PureBasiclang="purebasic">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)
Line 1,601 ⟶ 1,774:
 
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</langsyntaxhighlight>
 
=={{header|Python}}==
Line 1,609 ⟶ 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.
 
<langsyntaxhighlight lang="python">foo = object() # Create (instantiate) an empty object
address = id(foo)</langsyntaxhighlight>
 
In addition some folks have written binary Python modules which implement "peek" and "poke" operations, but these are non-standard.
 
=={{header|QBA64Quackery}}==
 
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.
<lang QB64>
 
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
Line 1,657 ⟶ 1,853:
_MemPut m(3), m(3).OFFSET, Saved.z
End Sub
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="qb64">
<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
Line 1,710 ⟶ 1,906:
_MemFree M
End
</syntaxhighlight>
</lang>
 
 
=={{header|R}}==
Line 1,717 ⟶ 1,912:
===With the library pryr===
 
<langsyntaxhighlight lang="rsplus">
x <- 5
y <- x
Line 1,727 ⟶ 1,922:
pryr::address(x)
pryr::address(y)
</syntaxhighlight>
</lang>
 
===Without any libraries===
<langsyntaxhighlight lang="rsplus">
address <- function(obj) {
paste0("0x", substring(sub(" .*$","",capture.output(.Internal(inspect(obj)))),2))
Line 1,743 ⟶ 1,938:
address(x)
address(y)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,754 ⟶ 1,949:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(require ffi/unsafe)
 
(define (madness v) ; i'm so sorry
(cast v _racket _gcpointer))</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="racket">
(ptr-ref (madness +) _short)
(ptr-ref (madness (/ 4 3)) _short)
Line 1,770 ⟶ 1,965:
(ptr-ref (madness #\a) _short)
(ptr-ref (madness 'foo) _short)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>my $x;
say $x.WHERE;
 
Line 1,784 ⟶ 1,979:
$x = 42;
say $y; # 42
</syntaxhighlight>
</lang>
{{out}}
<pre>7857931379550584425</pre>
How you set the address of a variable (or any other object) is outside the purview of the Perl 6 languageRaku, but Perl 6the 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}}==
<syntaxhighlight lang="vb">
<lang vb>
Dim TheAddress as long
Dim SecVar as byte
Line 1,810 ⟶ 2,005:
'SecVar is now also = 102
showmessage "SecVar = " + str$(SecVar)
</syntaxhighlight>
</lang>
 
=={{header|Retro}}==
Line 1,816 ⟶ 2,011:
 
===Get The Address===
<langsyntaxhighlight Retrolang="retro">'a var
&a</langsyntaxhighlight>
 
===Set The Address===
Create variable '''b''' and point it to address '''100'''
<langsyntaxhighlight Retrolang="retro">'b var
#100 @Dictionary d:xt store</langsyntaxhighlight>
 
===Byte Addressing===
Line 1,830 ⟶ 2,025:
To read the value at byte address 100:
 
<langsyntaxhighlight Retrolang="retro">'example/ByteAddressing.forth include
#100 b:fetch</langsyntaxhighlight>
 
Or to alter the value at byte address 100:
 
<syntaxhighlight lang Retro="retro">$e #100 b:store</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,843 ⟶ 2,038:
<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)
<langsyntaxhighlight lang="rexx">zzz = storage(xxx)</langsyntaxhighlight>
(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
Line 1,860 ⟶ 2,055:
For classes that do not override the <code>to_s</code> method, the <code>to_s</code> method also shows the address.
 
<langsyntaxhighlight lang="ruby">>foo = Object.new # => #<Object:0x10ae32000>
>id = foo.object_id # => 2238812160
>"%x" % (id << 1) # => "10ae32000"
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Line 1,869 ⟶ 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.
 
<langsyntaxhighlight lang="rust">let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
let mut v2;
Line 1,879 ⟶ 2,074:
// 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);</langsyntaxhighlight>
 
Get the memory address of a variable:
<langsyntaxhighlight lang="rust">let var = 1;
println!("address of var: {:p}", &var);</langsyntaxhighlight>
 
Get the value at a certain memory address:
<langsyntaxhighlight lang="rust">let address: usize = 0x7ffc8f303130;
unsafe {
let val = *(address as *const usize);
println!("value at {}: {:?}", address, val);
}</langsyntaxhighlight>
 
Set the value at a certain memory address:
<langsyntaxhighlight lang="rust">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);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 1,903 ⟶ 2,098:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">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</langsyntaxhighlight>
{{out}}
<pre>
Line 1,918 ⟶ 2,113:
You asked for it, and here it is:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|p|
p := Point x:10 y:20.
ObjectMemory addressOf:p.
ObjectMemory collectGarbage.
ObjectMemory addressOf:p "may return another value"</langsyntaxhighlight>
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}}{{works with|VisualWorks Smalltalk}}
<langsyntaxhighlight lang="smalltalk">|ptr|
ptr := ExternalBytes new:10.
ptr address.
ptr byteAt:1 put: 16rFF.</langsyntaxhighlight>
 
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:
<syntaxhighlight lang="text">|holder|
holder := ValueHolder with:123.
holder onChangeSend:#someChange to:someone.
holder value: 234
</syntaxhighlight>
</lang>
 
{{omit from|Smart BASIC}}
 
=={{header|Stata}}==
Line 1,944 ⟶ 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.
 
<langsyntaxhighlight lang="stata">a = 1
&a
 
Line 1,951 ⟶ 2,145:
}
 
&f()</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">
class MyClass { }
 
Line 1,984 ⟶ 2,178:
 
test()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,004 ⟶ 2,198:
<br>
{{libheader|critcl}}
<langsyntaxhighlight lang="tcl">package require critcl
# This code assumes an ILP32 architecture, like classic x86 or VAX.
critcl::cproc peek {int addr} int {
Line 2,024 ⟶ 2,218:
*u.a = value;
}
package provide poker 1.0</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">package require poker
 
# Increment a memory location; this will probably crash if you try for real.
Line 2,032 ⟶ 2,226:
# for embedded programming...
set where 0x12340
poke $where [expr {[peek $where] + 1}]</langsyntaxhighlight>
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 2,050 ⟶ 2,244:
foo .
 
{{omit from|TorqueScript}}
 
=={{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.
 
<langsyntaxhighlight lang="vb">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)
Line 2,078 ⟶ 2,271:
Call PutMem4(ptr, 87654321)
Debug.Print a
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 2,097 ⟶ 2,290:
 
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}}==
<langsyntaxhighlight lang="wart">addr.x
=> 27975840</langsyntaxhighlight>
 
<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.
 
<langsyntaxhighlight lang="wart">if (addr.x = addr.y)
..</langsyntaxhighlight>
 
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 2,115 ⟶ 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.
<langsyntaxhighlight ecmascriptlang="wren">var a = [1, 2, 3, 4]
var b = a // now 'a' and 'b' both point to the same List data
b[3] = 5
Line 2,121 ⟶ 2,324:
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")")</langsyntaxhighlight>
 
{{out}}
Line 2,132 ⟶ 2,335:
=={{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.)
<langsyntaxhighlight Assemblerlang="assembler"> movl my_variable, %eax</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Assemblerlang="assembler"> call eip_to_eax
addl $_GLOBAL_OFFSET_TABLE_, %eax
movl my_variable@GOT(%eax), %eax
Line 2,142 ⟶ 2,345:
eip_to_eax:
movl (%esp), %eax
ret</langsyntaxhighlight>
 
=={{header|XLISP}}==
To get the address in the heap of a variable <code>X</code>, use:
<syntaxhighlight lang ="lisp">(%ADDRESS-OF X)</langsyntaxhighlight>
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 2,160 ⟶ 2,363:
instead of a 32-bit relative address, when used on a 'real' variable.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int A, B;
[B:= addr A;
Line 2,166 ⟶ 2,369:
B(0):= $1234ABCD;
HexOut(0, A); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,196 ⟶ 2,399:
===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:
<langsyntaxhighlight 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</langsyntaxhighlight>
 
===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:
<langsyntaxhighlight lang="z80">foo equ &C000
bar equ &C001
 
Line 2,211 ⟶ 2,414:
 
ld de,bar
ld (de),a</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="z80">foo equ &C000
bar equ &C001
ld hl,foo
Line 2,223 ⟶ 2,426:
 
inc hl
ld (hl),c ;store the contents of C into bar</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight lang="z80">foo equ &C000
bar equ &C001
 
ld (foo),bc ;store C into "foo" and B into "bar"</langsyntaxhighlight>
 
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.
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{header|Zig}}==
{{works with|Zig|0.11.0}}
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
Line 2,248 ⟶ 2,452:
var address_of_i: *i32 = &i;
 
try stdout.print("{x}\n", .{@ptrToIntintFromPtr(address_of_i)});
}</langsyntaxhighlight>
 
{{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|AWK}}
{{omit from|bc|Impossible to access address of a variable}}
{{omit from|Brlcad}}
{{omit from|Clojure}}
{{omit from|Commodore BASIC}}
{{omit from|dc|Impossible to access address of a variable}}
{{omit from|Déjà Vu}}
{{omit from|E}}
{{omit from|Eiffel}}
{{omit from|Erlang}}
{{omit from|E}}
{{omit from|Factor}}
{{omit from|Falcon|Falcon does not support direct access of variable pointers}}
Line 2,267 ⟶ 2,477:
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|Icon}}
{{omit from|JavaScript}}
{{omit from|Joy}}
{{omit from|Icon}}{{omit from|UniconK}}
{{omit from|LaTeX}}
{{omit from|Lily}}
{{omit from|Lilypond}}
{{omit from|Lily}}
{{omit from|Logtalk}}
{{omit from|M4}}
{{omit from|Make}}
{{Omit From|MATLAB}}
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{Omit From|Metafont}}
{{omit from|ML/I}}
{{Omit From|MUMPS|The interpreter handles the addressing}}
{{omit from|NetRexx}}
{{Omit From|NSIS}}
{{omit from|OCaml}}
{{omit from|Octave}}
{{omit from|Openscad}}
{{omit from|Oz}}
{{omit from|PHP}}
{{omit from|PlainTeX}}
{{omit from|PHP}}
{{omit from|Scratch}}
{{omit from|Smart BASIC}}
{{omit from|TI-89 BASIC}}
{{omit from|TorqueScript}}
{{omit from|TPP}}
{{omit from|Unicon}}
{{omit from|UNIX Shell}}
{{omit from|Unlambda|Does not have variables.}}
{{omit from|Verilog}}
{{omit from|VHDL}}
{{omit from|XSLT}}
{{omit from|UNIX Shell}}
{{omit from|zkl}}
9,476

edits