Address of a variable: Difference between revisions

Content added Content deleted
m (→‎{{header|Raku}}: rake -> raku)
m (Automated syntax highlighting fixup (second round - minor fixes))
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):
<syntaxhighlight lang=360asm> LA R3,I load address of I
<syntaxhighlight lang="360asm"> LA R3,I load address of I
...
...
I DS F</syntaxhighlight>
I DS F</syntaxhighlight>
Line 15: Line 15:
===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):
<syntaxhighlight 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 25: Line 25:
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.
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.


<syntaxhighlight lang=6502asm>;;;;;;; zero page RAM memory addresses
<syntaxhighlight lang="6502asm">;;;;;;; zero page RAM memory addresses
CursorX equ $00
CursorX equ $00
CursorY equ $01
CursorY equ $01
Line 37: Line 37:
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.
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
<syntaxhighlight lang="6502asm">LDA #$20 ; load a constant into the accumulator


CLC
CLC
Line 48: Line 48:


6502 assemblers treat a number without a # in front as a memory address.
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
<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>
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:
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>
<syntaxhighlight lang="6502asm">byte $30,$20,$10,$00 ;these are constant numeric values, not memory addresses.</syntaxhighlight>


=={{header|68000 Assembly}}==
=={{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.
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
<syntaxhighlight lang="68000devpac">UserRam equ $100000
Cursor_X equ UserRam ;$100000, byte length
Cursor_X equ UserRam ;$100000, byte length
Cursor_Y equ UserRam+1 ;$100001, byte length
Cursor_Y equ UserRam+1 ;$100001, byte length
Line 69: Line 69:
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.
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
<syntaxhighlight lang="68000devpac">MOVE.L #$11223344,D0
MOVE.L D0,(A0) ; store D0 into ThirtyTwoBitData ($100004)
MOVE.L D0,(A0) ; store D0 into ThirtyTwoBitData ($100004)
; HEXDUMP OF $100004:
; HEXDUMP OF $100004:
Line 83: Line 83:
{{works with|https://www.dosbox.com DOSBox}}
{{works with|https://www.dosbox.com DOSBox}}
===Get The Address===
===Get The Address===
<syntaxhighlight lang=asm>.model small
<syntaxhighlight lang="asm">.model small
.stack 1024
.stack 1024
.data
.data
Line 101: 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.
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
<syntaxhighlight lang="asm">mov ax, 0FFFFh
mov [es:di],ax ;store 0xFFFF into the base address of UserRam.</syntaxhighlight>
mov [es:di],ax ;store 0xFFFF into the base address of UserRam.</syntaxhighlight>


Alternatively, this would also work:
Alternatively, this would also work:
<syntaxhighlight lang=asm>.model small
<syntaxhighlight lang="asm">.model small
.stack 1024
.stack 1024
.data
.data
Line 122: Line 122:
=={{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>
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AArch64 Raspberry PI 3B */
/* ARM assembly AArch64 Raspberry PI 3B */
/* program adrvar.s */
/* program adrvar.s */
Line 200: Line 200:


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


Line 215: Line 215:
=={{header|Ada}}==
=={{header|Ada}}==
===Get The Address===
===Get The Address===
<syntaxhighlight lang=ada>The_Address : System.Address;
<syntaxhighlight lang="ada">The_Address : System.Address;
I : Integer;
I : Integer;
The_Address := I'Address;</syntaxhighlight>
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
<syntaxhighlight lang=ada>I : Integer;
<syntaxhighlight lang="ada">I : Integer;
for I'Address use 16#A100#;</syntaxhighlight>
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.
<syntaxhighlight lang=ada>I : Integer;
<syntaxhighlight lang="ada">I : Integer;
J : Integer;
J : Integer;
for I'Address use J'Address;</syntaxhighlight>
for I'Address use J'Address;</syntaxhighlight>
Line 233: 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.
<syntaxhighlight 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;
Line 250: 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:<syntaxhighlight lang=algol68>PROC establish = (REF FILE file, STRING idf, CHANNEL chan, INT p, l, c) INT: ~</syntaxhighlight>
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 262: Line 262:
=== Get the address ===
=== Get the address ===
Get the address of the last variable used.
Get the address of the last variable used.
<syntaxhighlight lang=ApplesoftBasic>N = N : PRINT PEEK (131) + PEEK (132) * 256</syntaxhighlight>
<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.
<syntaxhighlight 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
Line 271: Line 271:
=== 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.
<syntaxhighlight 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>
</syntaxhighlight>
Set the address and length of a string.
Set the address and length of a string.
<syntaxhighlight 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
Line 281: Line 281:
</syntaxhighlight>
</syntaxhighlight>
Set the address of a function.
Set the address of a function.
<syntaxhighlight 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 296: Line 296:
=== Get the address ===
=== Get the address ===
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<syntaxhighlight 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 :)
Line 306: Line 306:
that returns a reference.
that returns a reference.
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<syntaxhighlight 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 :)
Line 313: Line 313:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 388: Line 388:
=={{header|Arturo}}==
=={{header|Arturo}}==


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


Line 401: Line 401:


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


Line 413: Line 413:
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
<syntaxhighlight lang=AutoHotkey>msgbox % &var</syntaxhighlight>
<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:
<syntaxhighlight lang=axe>°A→B
<syntaxhighlight lang="axe">°A→B
.B now contains the address of A</syntaxhighlight>
.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:
<syntaxhighlight lang=axe>1234→A
<syntaxhighlight lang="axe">1234→A
1→{A}</syntaxhighlight>
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.
Line 428: Line 428:
=={{header|BaCon}}==
=={{header|BaCon}}==


<syntaxhighlight lang=freebasic>
<syntaxhighlight lang="freebasic">
'---get a variable's address
'---get a variable's address
LOCAL x TYPE long
LOCAL x TYPE long
Line 436: Line 436:
=={{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).
<syntaxhighlight 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 447: Line 447:
=={{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:
<syntaxhighlight lang=bbcbasic>REM get a variable's address:
<syntaxhighlight lang="bbcbasic">REM get a variable's address:
y% = ^x%
y% = ^x%


Line 460: Line 460:
=== 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>.
<syntaxhighlight lang=cpp>int i;
<syntaxhighlight lang="cpp">int i;
void* address_of_i = &i;</syntaxhighlight>
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>:


<syntaxhighlight lang=cpp>#include <memory>
<syntaxhighlight lang="cpp">#include <memory>
int i;
int i;
auto address_of_i = std::addressof(i);</syntaxhighlight>
auto address_of_i = std::addressof(i);</syntaxhighlight>
Line 471: Line 471:
=== 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:
<syntaxhighlight lang=cpp>int& i = *(int*)0xA100;</syntaxhighlight>
<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:
<syntaxhighlight 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;</syntaxhighlight>
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):
<syntaxhighlight lang=cpp>static union
<syntaxhighlight lang="cpp">static union
{
{
int i;
int i;
Line 485: Line 485:
};</syntaxhighlight>
};</syntaxhighlight>
'''C++ only:''' An alternative (and cleaner) solution is to use references:
'''C++ only:''' An alternative (and cleaner) solution is to use references:
<syntaxhighlight lang=cpp>int i;
<syntaxhighlight lang="cpp">int i;
int& j = i;</syntaxhighlight>
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.
Line 491: Line 491:
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>:


<syntaxhighlight 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);</syntaxhighlight>
float f = read_as_float(i);</syntaxhighlight>


{{omit from|Clojure}}


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 505: Line 504:
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*.


<syntaxhighlight lang=csharp>unsafe
<syntaxhighlight lang="csharp">unsafe
{
{
int i = 5;
int i = 5;
Line 515: Line 514:


===Get Address===
===Get Address===
<syntaxhighlight lang=cobol>data division.
<syntaxhighlight lang="cobol">data division.
working-storage section.
working-storage section.
01 ptr usage pointer.
01 ptr usage pointer.
Line 525: Line 524:
===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.
<syntaxhighlight 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
Line 547: Line 546:
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:


<syntaxhighlight 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 578: Line 577:
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.


<syntaxhighlight 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 617: Line 616:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE AddressVar;
MODULE AddressVar;
IMPORT SYSTEM,StdLog;
IMPORT SYSTEM,StdLog;
Line 640: Line 639:


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


Line 718: Line 717:


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


Using a numeric value:
Using a numeric value:
<syntaxhighlight lang=d>int* ip = cast(int*)0xdeadf00d;</syntaxhighlight>
<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 728: Line 727:
The closest thing is passing a dereferenced pointer to a reference parameter.
The closest thing is passing a dereferenced pointer to a reference parameter.


<syntaxhighlight 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 742: Line 741:


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:
<syntaxhighlight lang=pascal>var
<syntaxhighlight lang="pascal">var
i: integer;
i: integer;
p: ^integer;
p: ^integer;
Line 752: Line 751:


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:
<syntaxhighlight lang=pascal>var
<syntaxhighlight lang="pascal">var
crtMode: integer absolute $0040;
crtMode: integer absolute $0040;
str: string[100];
str: string[100];
Line 759: Line 758:


=={{header|Draco}}==
=={{header|Draco}}==
<syntaxhighlight lang=draco>/* This code uses a CP/M-specific address to demonstrate fixed locations,
<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 */
* so it will very likely only work under CP/M */
proc nonrec main() void:
proc nonrec main() void:
Line 795: Line 794:
=={{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
Line 803: Line 802:
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 868: Line 867:
=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<syntaxhighlight lang=fortran>program test_loc
<syntaxhighlight lang="fortran">program test_loc
implicit none
implicit none


Line 882: Line 881:
=={{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:
<syntaxhighlight 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 </syntaxhighlight>
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:
<syntaxhighlight lang=freebasic>Var p = Cast(Integer Ptr, 1375832)
<syntaxhighlight lang="freebasic">Var p = Cast(Integer Ptr, 1375832)
*p = 42
*p = 42
Print p, *p</syntaxhighlight>
Print p, *p</syntaxhighlight>


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


short i = 575
short i = 575
Line 927: Line 926:
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.
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 977: Line 976:


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


Line 1,013: Line 1,012:
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</syntaxhighlight>
new_var =: 15!:7 var_addr NB. Set address</syntaxhighlight>
Line 1,027: Line 1,026:
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>: <syntaxhighlight 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 1,036: Line 1,035:
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.
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:<syntaxhighlight 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 1,061: Line 1,060:
3.14149</syntaxhighlight>
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>:<syntaxhighlight 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 1,070: Line 1,069:
3.14149</syntaxhighlight>
3.14149</syntaxhighlight>


{{omit from|K}}


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Line 1,077: Line 1,075:
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}}
<syntaxhighlight lang=scala>// Kotlin Native v0.5
<syntaxhighlight lang="scala">// Kotlin Native v0.5


import kotlinx.cinterop.*
import kotlinx.cinterop.*
Line 1,098: Line 1,096:
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>
<syntaxhighlight lang="scheme">


1) lambdas
1) lambdas
Line 1,127: Line 1,125:
=={{header|Lua}}==
=={{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.
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 = {}
<syntaxhighlight lang="lua">t = {}
print(t)
print(t)
f = function() end
f = function() end
Line 1,148: Line 1,146:


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>.
<syntaxhighlight lang=Maple>> addressof( x );
<syntaxhighlight lang="maple">> addressof( x );
18446884674469911422</syntaxhighlight>The inverse operation is <code>pointto</code>:<syntaxhighlight lang=Maple>
18446884674469911422</syntaxhighlight>The inverse operation is <code>pointto</code>:<syntaxhighlight lang="maple">
> pointto( 18446884674469911422 );
> pointto( 18446884674469911422 );
x</syntaxhighlight>This works for any expression, not just variables:<syntaxhighlight 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


Line 1,160: Line 1,158:
=={{header|Modula-2}}==
=={{header|Modula-2}}==
===Get Address===
===Get Address===
<syntaxhighlight lang=modula2>MODULE GetAddress;
<syntaxhighlight lang="modula2">MODULE GetAddress;


FROM SYSTEM IMPORT ADR;
FROM SYSTEM IMPORT ADR;
Line 1,174: Line 1,172:


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


CONST adress = 134664460;
CONST adress = 134664460;
Line 1,186: Line 1,184:
=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
===Get Address===
===Get Address===
<syntaxhighlight lang=nanoquery>import native
<syntaxhighlight lang="nanoquery">import native


a = 5
a = 5
Line 1,196: Line 1,194:
===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.
<syntaxhighlight lang=nanoquery>import native
<syntaxhighlight lang="nanoquery">import native


a = 123
a = 123
Line 1,212: Line 1,210:
=={{header|NewLISP}}==
=={{header|NewLISP}}==
===Get Address===
===Get Address===
<syntaxhighlight lang=NewLISP>
<syntaxhighlight lang="newlisp">
(set 'a '(1 2 3))
(set 'a '(1 2 3))
(address a)
(address a)
Line 1,218: Line 1,216:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight 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
Line 1,248: Line 1,246:
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:


<syntaxhighlight 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,270: Line 1,268:
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 :


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


Line 1,311: Line 1,309:


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


Line 1,359: Line 1,357:
=={{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
<syntaxhighlight lang=parigp>issquare(n, &m)</syntaxhighlight>
<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,371: Line 1,369:
=={{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.
<syntaxhighlight lang=perl>use Scalar::Util qw(refaddr);
<syntaxhighlight lang="perl">use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; # 140502490125712</syntaxhighlight>
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>:
<syntaxhighlight lang=perl>printf "%p", $v; # 7fc949039590</syntaxhighlight>
<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,380: Line 1,378:


Simple reference (address) manipulation.
Simple reference (address) manipulation.
<syntaxhighlight 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
Line 1,386: Line 1,384:


Example how to make variable overlay.
Example how to make variable overlay.
<syntaxhighlight 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;
Line 1,407: Line 1,405:
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.
<!--<syntaxhighlight 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,446: Line 1,444:
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.
<syntaxhighlight lang=PicoLisp>: (setq X 7)
<syntaxhighlight lang="picolisp">: (setq X 7)
-> 7
-> 7


Line 1,463: Line 1,461:
=={{header|PL/I}}==
=={{header|PL/I}}==


<syntaxhighlight lang=PL/I>
<syntaxhighlight 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,500: Line 1,498:


=={{header|PL/M}}==
=={{header|PL/M}}==
<syntaxhighlight lang=pli>100H:
<syntaxhighlight lang="pli">100H:
/* THERE IS NO STANDARD LIBRARY
/* THERE IS NO STANDARD LIBRARY
THIS DEFINES SOME BASIC I/O USING CP/M */
THIS DEFINES SOME BASIC I/O USING CP/M */
Line 1,588: Line 1,586:


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
<syntaxhighlight 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,609: Line 1,607:
=={{header|PureBasic}}==
=={{header|PureBasic}}==
Get the address of a variable using the '@' operator.
Get the address of a variable using the '@' operator.
<syntaxhighlight lang=PureBasic>a.i = 5
<syntaxhighlight lang="purebasic">a.i = 5
MessageRequester("Address",Str(@a))</syntaxhighlight>
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).
<syntaxhighlight 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,628: Line 1,626:
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.


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


Line 1,635: Line 1,633:
=={{header|QB64}}==
=={{header|QB64}}==


<syntaxhighlight lang=QB64>
<syntaxhighlight lang="qb64">
' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions
' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions
Type points
Type points
Line 1,678: Line 1,676:
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang=QB64>
<syntaxhighlight lang="qb64">
' Full demonstration of being together Qbasic and QB64 methods for accessing and modifying memory directly
' 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
Dim A As Integer, B As String, C(1 To 4) As Double
Line 1,735: Line 1,733:
===With the library pryr===
===With the library pryr===


<syntaxhighlight lang=rsplus>
<syntaxhighlight lang="rsplus">
x <- 5
x <- 5
y <- x
y <- x
Line 1,748: Line 1,746:


===Without any libraries===
===Without any libraries===
<syntaxhighlight 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,772: Line 1,770:


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


(require ffi/unsafe)
(require ffi/unsafe)
Line 1,781: Line 1,779:
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.


<syntaxhighlight 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,808: Line 1,806:


=={{header|RapidQ}}==
=={{header|RapidQ}}==
<syntaxhighlight lang=vb>
<syntaxhighlight lang="vb">
Dim TheAddress as long
Dim TheAddress as long
Dim SecVar as byte
Dim SecVar as byte
Line 1,834: Line 1,832:


===Get The Address===
===Get The Address===
<syntaxhighlight lang=Retro>'a var
<syntaxhighlight lang="retro">'a var
&a</syntaxhighlight>
&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'''
<syntaxhighlight lang=Retro>'b var
<syntaxhighlight lang="retro">'b var
#100 @Dictionary d:xt store</syntaxhighlight>
#100 @Dictionary d:xt store</syntaxhighlight>


Line 1,848: Line 1,846:
To read the value at byte address 100:
To read the value at byte address 100:


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


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


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


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,861: Line 1,859:
<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)
<syntaxhighlight lang=rexx>zzz = storage(xxx)</syntaxhighlight>
<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,878: Line 1,876:
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.


<syntaxhighlight 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"
Line 1,887: Line 1,885:
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.


<syntaxhighlight 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,900: Line 1,898:


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


Get the value at a certain memory address:
Get the value at a certain memory address:
<syntaxhighlight 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);
Line 1,911: Line 1,909:


Set the value at a certain memory address:
Set the value at a certain memory address:
<syntaxhighlight 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.
Line 1,921: Line 1,919:


=={{header|Sidef}}==
=={{header|Sidef}}==
<syntaxhighlight 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</syntaxhighlight>
say Sys.refaddr(n); # prints the address of the object at which the variable points to</syntaxhighlight>
Line 1,936: Line 1,934:
You asked for it, and here it is:
You asked for it, and here it is:
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<syntaxhighlight 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.
Line 1,944: Line 1,942:
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}}
<syntaxhighlight lang=smalltalk>|ptr|
<syntaxhighlight lang="smalltalk">|ptr|
ptr := ExternalBytes new:10.
ptr := ExternalBytes new:10.
ptr address.
ptr address.
Line 1,950: Line 1,948:


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.
Line 1,956: Line 1,954:
</syntaxhighlight>
</syntaxhighlight>


{{omit from|Smart BASIC}}


=={{header|Stata}}==
=={{header|Stata}}==
Line 1,962: Line 1,959:
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.


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


Line 1,972: Line 1,969:


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


Line 2,022: Line 2,019:
<br>
<br>
{{libheader|critcl}}
{{libheader|critcl}}
<syntaxhighlight 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 2,044: Line 2,041:
package provide poker 1.0</syntaxhighlight>
package provide poker 1.0</syntaxhighlight>
Demonstrating:
Demonstrating:
<syntaxhighlight 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 2,068: Line 2,065:
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.


<syntaxhighlight 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 2,117: Line 2,113:


=={{header|Wart}}==
=={{header|Wart}}==
<syntaxhighlight lang=wart>addr.x
<syntaxhighlight lang="wart">addr.x
=> 27975840</syntaxhighlight>
=> 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.


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


Line 2,133: Line 2,129:


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.
<syntaxhighlight lang=ecmascript>var a = [1, 2, 3, 4]
<syntaxhighlight lang="ecmascript">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 2,150: Line 2,146:
=={{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.)
<syntaxhighlight lang=Assembler> movl my_variable, %eax</syntaxhighlight>
<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.


<syntaxhighlight 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 2,164: Line 2,160:
=={{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:
<syntaxhighlight lang=lisp>(%ADDRESS-OF X)</syntaxhighlight>
<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 2,178: Line 2,174:
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.


<syntaxhighlight 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 2,214: Line 2,210:
===Specifying a Memory Location===
===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:
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
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
bar equ &C001
ld (foo),a ;store A into memory location &C000
ld (foo),a ;store A into memory location &C000
Line 2,222: Line 2,218:
===Using BC or DE===
===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:
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
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
bar equ &C001


Line 2,233: Line 2,229:
===Using HL===
===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.
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
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
bar equ &C001
ld hl,foo
ld hl,foo
Line 2,246: Line 2,242:
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.
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
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
bar equ &C001


Line 2,252: Line 2,248:


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.
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
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
bar equ &C001


Line 2,259: Line 2,255:


=={{header|Zig}}==
=={{header|Zig}}==
<syntaxhighlight lang=zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
pub fn main() !void {
pub fn main() !void {
Line 2,269: Line 2,265:
}</syntaxhighlight>
}</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 2,285: Line 2,287:
{{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|PlainTeX}}
{{omit from|PHP}}
{{omit from|PHP}}
{{omit from|PlainTeX}}
{{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}}