Address of a variable: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (→‎{{header|Raku}}: rake -> raku)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 9:
===Get the Address===
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
...
I DS F</syntaxhighlight>
Line 15:
===Set the Address===
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
LA R12,I set @J=@I
L R2,J now J is at the same location as I
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.
 
<syntaxhighlight lang="6502asm">;;;;;;; zero page RAM memory addresses
CursorX equ $00
CursorY equ $01
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.
 
<syntaxhighlight lang="6502asm">LDA #$20 ; load a constant into the accumulator
 
CLC
Line 48:
 
6502 assemblers treat a number without a # in front as a memory address.
<syntaxhighlight lang="6502asm">LDA #$30 ;load into the accumulator the constant value 0x30
LDA $30 ;load into the accumulator the value stored at memory address 0x0030.</syntaxhighlight>
 
The only exception to this rule is when defining bytes. These do not have # in front, but are treated as constants nonetheless:
<syntaxhighlight lang="6502asm">byte $30,$20,$10,$00 ;these are constant numeric values, not memory addresses.</syntaxhighlight>
 
=={{header|68000 Assembly}}==
When programming in assembly language yourself, generally the addresses of variables are known in advance and chosen by the programmer rather than dynamically determined by the compiler. Therefore you pretty much always know a variable's address at all times.
 
<syntaxhighlight lang="68000devpac">UserRam equ $100000
Cursor_X equ UserRam ;$100000, byte length
Cursor_Y equ UserRam+1 ;$100001, byte length
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.
 
<syntaxhighlight lang="68000devpac">MOVE.L #$11223344,D0
MOVE.L D0,(A0) ; store D0 into ThirtyTwoBitData ($100004)
; HEXDUMP OF $100004:
Line 83:
{{works with|https://www.dosbox.com DOSBox}}
===Get The Address===
<syntaxhighlight lang="asm">.model small
.stack 1024
.data
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.
 
<syntaxhighlight lang="asm">mov ax, 0FFFFh
mov [es:di],ax ;store 0xFFFF into the base address of UserRam.</syntaxhighlight>
 
Alternatively, this would also work:
<syntaxhighlight lang="asm">.model small
.stack 1024
.data
Line 122:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AArch64 Raspberry PI 3B */
/* program adrvar.s */
Line 200:
 
=={{header|Action!}}==
<syntaxhighlight lang=Action"action!">PROC Main()
BYTE v=[123]
 
Line 215:
=={{header|Ada}}==
===Get The Address===
<syntaxhighlight lang="ada">The_Address : System.Address;
I : Integer;
The_Address := I'Address;</syntaxhighlight>
===Set The Address===
Set the address of a variable to address A100 in hexadecimal
<syntaxhighlight lang="ada">I : Integer;
for I'Address use 16#A100#;</syntaxhighlight>
Set the address of one variable to the address of another variable, creating an overlay.
<syntaxhighlight lang="ada">I : Integer;
J : Integer;
for I'Address use J'Address;</syntaxhighlight>
Line 233:
But the value of the actual address is not available
for printing or any arithmetic.
<syntaxhighlight lang="algol68">[4]INT test := (222,444,666,888);
REF INT reference := test[3];
REF INT(reference) := reference + 111;
Line 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:<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
options. And <tt>chan</tt> is the actual device type. Standard CHANNELs in
Line 262:
=== Get the address ===
Get the address of the last variable used.
<syntaxhighlight lang=ApplesoftBasic"applesoftbasic">N = N : PRINT PEEK (131) + PEEK (132) * 256</syntaxhighlight>
Get (find) the address of a function.
<syntaxhighlight lang=ApplesoftBasic"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
Line 271:
=== Set the address ===
Set the address where variables are stored, but clears all variables.
<syntaxhighlight lang=ApplesoftBasic"applesoftbasic">LOMEM: 4096
I% = I% : PRINT PEEK (131) + PEEK (132) * 256
</syntaxhighlight>
Set the address and length of a string.
<syntaxhighlight lang=ApplesoftBasic"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
Line 281:
</syntaxhighlight>
Set the address of a function.
<syntaxhighlight lang=ApplesoftBasic"applesoftbasic">0 DEF FN F(X) = 1
1 DEF FN B(X) = 2
2 N$ = "F" : GOSUB 8 : FA = A
Line 296:
=== Get the address ===
{{works with|Argile|1.0.0}}
<syntaxhighlight lang=Argile"argile">use std, array (: array.arg also defines pointer operators :)
let var = 42
let ptr = &var (: value of ptr is address of var :)
Line 306:
that returns a reference.
{{works with|Argile|1.0.0}}
<syntaxhighlight lang=Argile"argile">use std, array
=:mac:= -> int& { * (0x400000 as int*) }
printf "%x\n" mac (: may crash depending on operating system :)
Line 313:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
 
/* ARM assembly Raspberry PI */
Line 388:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">x: 2
xInfo: info.get 'x
 
Line 401:
 
=={{header|Astro}}==
<syntaxhighlight lang="python">var num = 12
var pointer = ptr(num) # get pointer
 
Line 413:
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</syntaxhighlight>
 
=={{header|Axe}}==
 
Axe supports getting the address of a variable using the degree symbol:
<syntaxhighlight lang="axe">°A→B
.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:
<syntaxhighlight lang="axe">1234→A
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.
Line 428:
=={{header|BaCon}}==
 
<syntaxhighlight lang="freebasic">
'---get a variable's address
LOCAL x TYPE long
Line 436:
=={{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).
<syntaxhighlight lang="qbasic">'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
Line 447:
=={{header|BBC BASIC}}==
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:
y% = ^x%
 
Line 460:
=== 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>.
<syntaxhighlight lang="cpp">int i;
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>:
 
<syntaxhighlight lang="cpp">#include <memory>
int i;
auto address_of_i = std::addressof(i);</syntaxhighlight>
Line 471:
=== 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:
<syntaxhighlight lang="cpp">int& i = *(int*)0xA100;</syntaxhighlight>
 
If the type of the variable requires initialization, it is necessary to use placement new:
<syntaxhighlight lang="cpp">#include <new>
struct S { int i = 0; S() {} };
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):
<syntaxhighlight lang="cpp">static union
{
int i;
Line 485:
};</syntaxhighlight>
'''C++ only:''' An alternative (and cleaner) solution is to use references:
<syntaxhighlight lang="cpp">int i;
int& j = i;</syntaxhighlight>
Note that in this case, the variables can be non-static.
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>:
 
<syntaxhighlight 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);</syntaxhighlight>
 
{{omit from|Clojure}}
 
=={{header|C sharp|C#}}==
Line 505 ⟶ 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*.
 
<syntaxhighlight lang="csharp">unsafe
{
int i = 5;
Line 515 ⟶ 514:
 
===Get Address===
<syntaxhighlight lang="cobol">data division.
working-storage section.
01 ptr usage pointer.
Line 525 ⟶ 524:
===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.
<syntaxhighlight lang="cobol">
OCOBOL*> Rosetta Code set address example
*> tectonics: cobc -x setaddr.cob && ./setaddr
Line 547 ⟶ 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:
 
<syntaxhighlight 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 578 ⟶ 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.
 
<syntaxhighlight lang="lisp">(use-package :ffi)
 
(defmacro def-libc-call-out (name &rest args)
Line 617 ⟶ 616:
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE AddressVar;
IMPORT SYSTEM,StdLog;
Line 640 ⟶ 639:
 
=={{header|Creative Basic}}==
<syntaxhighlight lang=Creative"creative Basicbasic">
== Get ==
 
Line 718 ⟶ 717:
 
Take the address of a variable:
<syntaxhighlight lang="d">int i;
int* ip = &i;</syntaxhighlight>
 
Using a numeric value:
<syntaxhighlight lang="d">int* ip = cast(int*)0xdeadf00d;</syntaxhighlight>
 
Locating a "regular" variable at a specific address is not possible.
Line 728 ⟶ 727:
The closest thing is passing a dereferenced pointer to a reference parameter.
 
<syntaxhighlight lang="d">void test(ref int i) {
import std.stdio;
writeln(&i);
Line 742 ⟶ 741:
 
To get the address of any variable, structure, procedure or function use the <tt>@</tt>-operator:
<syntaxhighlight lang="pascal">var
i: integer;
p: ^integer;
Line 752 ⟶ 751:
 
A variable can be declared as <tt>absolute</tt> i. e.: to reside at a specific address:
<syntaxhighlight lang="pascal">var
crtMode: integer absolute $0040;
str: string[100];
Line 759 ⟶ 758:
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">/* This code uses a CP/M-specific address to demonstrate fixed locations,
* so it will very likely only work under CP/M */
proc nonrec main() void:
Line 795 ⟶ 794:
=={{header|ERRE}}==
ERRE hasn't explicit pointers, but only a function that gets the address of a variable
<syntaxhighlight lang="text">
........
A%=100
Line 803 ⟶ 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.
Using this address you can modify the variable's value without using an assignment statement:
<syntaxhighlight lang="text">
PROGRAM POINTER
BEGIN
Line 868 ⟶ 867:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<syntaxhighlight lang="fortran">program test_loc
implicit none
 
Line 882 ⟶ 881:
=={{header|FreeBASIC}}==
One can get the address of a variable using the @ operator:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
Dim a As Integer = 3
Dim p As Integer Ptr = @a
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:
<syntaxhighlight lang="freebasic">Var p = Cast(Integer Ptr, 1375832)
*p = 42
Print p, *p</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1
 
short i = 575
Line 927 ⟶ 926:
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.
<syntaxhighlight lang="go">package main
 
import (
Line 977 ⟶ 976:
 
=={{header|IWBASIC}}==
<syntaxhighlight lang=IWBASIC"iwbasic">
== Get ==
 
Line 1,013 ⟶ 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:
 
<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</syntaxhighlight>
Line 1,027 ⟶ 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.
 
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)
Ptr{Void} @0x000000010282e4a0
Line 1,036 ⟶ 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.
 
<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}:
1.0
Line 1,061 ⟶ 1,060:
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>
julia> q = convert(Ptr{Float64}, 0x0000000113f70d68)
Ptr{Float64} @0x0000000113f70d68
Line 1,070 ⟶ 1,069:
3.14149</syntaxhighlight>
 
{{omit from|K}}
 
=={{header|Kotlin}}==
Line 1,077 ⟶ 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.
{{works with|Ubuntu|14.04}}
<syntaxhighlight lang="scala">// Kotlin Native v0.5
 
import kotlinx.cinterop.*
Line 1,098 ⟶ 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:
 
<syntaxhighlight lang=Scheme"scheme">
 
1) lambdas
Line 1,127 ⟶ 1,125:
=={{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
Line 1,148 ⟶ 1,146:
 
To obtain the address of any expression in Maple, use the builtin function <code>addressof</code>.
<syntaxhighlight lang=Maple"maple">> addressof( x );
18446884674469911422</syntaxhighlight>The inverse operation is <code>pointto</code>:<syntaxhighlight lang=Maple"maple">
> pointto( 18446884674469911422 );
x</syntaxhighlight>This works for any expression, not just variables:<syntaxhighlight lang=Maple"maple">> addressof( sin( x )^2 + cos( x )^2 );
18446884674469972158
 
Line 1,160 ⟶ 1,158:
=={{header|Modula-2}}==
===Get Address===
<syntaxhighlight lang="modula2">MODULE GetAddress;
 
FROM SYSTEM IMPORT ADR;
Line 1,174 ⟶ 1,172:
 
===Set Address===
<syntaxhighlight lang="modula2">MODULE SetAddress;
 
CONST adress = 134664460;
Line 1,186 ⟶ 1,184:
=={{header|Nanoquery}}==
===Get Address===
<syntaxhighlight lang="nanoquery">import native
 
a = 5
Line 1,196 ⟶ 1,194:
===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.
<syntaxhighlight lang="nanoquery">import native
 
a = 123
Line 1,212 ⟶ 1,210:
=={{header|NewLISP}}==
===Get Address===
<syntaxhighlight lang=NewLISP"newlisp">
(set 'a '(1 2 3))
(address a)
Line 1,218 ⟶ 1,216:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">var x = 12
var xptr = addr(x) # Get address of variable
echo cast[int](xptr) # and print it
Line 1,248 ⟶ 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:
 
<syntaxhighlight 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,270 ⟶ 1,268:
For instance, here, after creating and setting a variable A, we store the corresponding word into a variable B :
 
<syntaxhighlight lang=Oforth"oforth">tvar: A
10 to A
 
Line 1,311 ⟶ 1,309:
 
=={{header|Panoramic}}==
<syntaxhighlight lang=Panoramic"panoramic">
== Get ==
 
Line 1,359 ⟶ 1,357:
=={{header|PARI/GP}}==
In GP you can sent the address to built-in commands like issquare
<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
<pre>\x</pre>
Line 1,371 ⟶ 1,369:
=={{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.
<syntaxhighlight lang="perl">use Scalar::Util qw(refaddr);
print refaddr(\my $v), "\n"; # 140502490125712</syntaxhighlight>
Alternatively, the address (in hexadecimal) can be directly obtained with <code>printf</code>:
<syntaxhighlight lang="perl">printf "%p", $v; # 7fc949039590</syntaxhighlight>
Use Devel::Pointer::PP if you want to dereference a certain address in memory.
 
Line 1,380 ⟶ 1,378:
 
Simple reference (address) manipulation.
<syntaxhighlight lang="perl">my $a = 12;
my $b = \$a; # get reference
$$b = $$b + 30; # access referenced value
Line 1,386 ⟶ 1,384:
 
Example how to make variable overlay.
<syntaxhighlight lang="perl">my $a = 12;
our $b; # you can overlay only global variables (this line is only for strictness)
*b = \$a;
Line 1,407 ⟶ 1,405:
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.
<!--<syntaxhighlight lang=Phix"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,446 ⟶ 1,444:
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.
<syntaxhighlight lang=PicoLisp"picolisp">: (setq X 7)
-> 7
 
Line 1,463 ⟶ 1,461:
=={{header|PL/I}}==
 
<syntaxhighlight lang=PL"pl/Ii">
declare addr builtin; /* retrieve address of a variable */
declare ptradd builtin; /* pointer addition */
Line 1,500 ⟶ 1,498:
 
=={{header|PL/M}}==
<syntaxhighlight lang="pli">100H:
/* THERE IS NO STANDARD LIBRARY
THIS DEFINES SOME BASIC I/O USING CP/M */
Line 1,588 ⟶ 1,586:
 
=={{header|PowerBASIC}}==
<syntaxhighlight lang="powerbasic">'get a variable's address:
DIM x AS INTEGER, y AS LONG
y = VARPTR(x)
Line 1,609 ⟶ 1,607:
=={{header|PureBasic}}==
Get the address of a variable using the '@' operator.
<syntaxhighlight lang=PureBasic"purebasic">a.i = 5
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).
<syntaxhighlight lang=PureBasic"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,628 ⟶ 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.
 
<syntaxhighlight lang="python">foo = object() # Create (instantiate) an empty object
address = id(foo)</syntaxhighlight>
 
Line 1,635 ⟶ 1,633:
=={{header|QB64}}==
 
<syntaxhighlight lang=QB64"qb64">
' Adapted from QB64wiki example a demo of _MEM type data and _MEM functions
Type points
Line 1,678 ⟶ 1,676:
</syntaxhighlight>
 
<syntaxhighlight lang=QB64"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,735 ⟶ 1,733:
===With the library pryr===
 
<syntaxhighlight lang="rsplus">
x <- 5
y <- x
Line 1,748 ⟶ 1,746:
 
===Without any libraries===
<syntaxhighlight lang="rsplus">
address <- function(obj) {
paste0("0x", substring(sub(" .*$","",capture.output(.Internal(inspect(obj)))),2))
Line 1,772 ⟶ 1,770:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
 
(require ffi/unsafe)
Line 1,781 ⟶ 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.
 
<syntaxhighlight lang="racket">
(ptr-ref (madness +) _short)
(ptr-ref (madness (/ 4 3)) _short)
Line 1,808 ⟶ 1,806:
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
Dim TheAddress as long
Dim SecVar as byte
Line 1,834 ⟶ 1,832:
 
===Get The Address===
<syntaxhighlight lang=Retro"retro">'a var
&a</syntaxhighlight>
 
===Set The Address===
Create variable '''b''' and point it to address '''100'''
<syntaxhighlight lang=Retro"retro">'b var
#100 @Dictionary d:xt store</syntaxhighlight>
 
Line 1,848 ⟶ 1,846:
To read the value at byte address 100:
 
<syntaxhighlight lang=Retro"retro">'example/ByteAddressing.forth include
#100 b:fetch</syntaxhighlight>
 
Or to alter the value at byte address 100:
 
<syntaxhighlight lang=Retro"retro">$e #100 b:store</syntaxhighlight>
 
=={{header|REXX}}==
Line 1,861 ⟶ 1,859:
<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)
<syntaxhighlight lang="rexx">zzz = storage(xxx)</syntaxhighlight>
(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,878 ⟶ 1,876:
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>
>id = foo.object_id # => 2238812160
>"%x" % (id << 1) # => "10ae32000"
Line 1,887 ⟶ 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.
 
<syntaxhighlight lang="rust">let v1 = vec![vec![1,2,3]; 10];
println!("Original address: {:p}", &v1);
let mut v2;
Line 1,900 ⟶ 1,898:
 
Get the memory address of a variable:
<syntaxhighlight lang="rust">let var = 1;
println!("address of var: {:p}", &var);</syntaxhighlight>
 
Get the value at a certain memory address:
<syntaxhighlight lang="rust">let address: usize = 0x7ffc8f303130;
unsafe {
let val = *(address as *const usize);
Line 1,911 ⟶ 1,909:
 
Set the value at a certain memory address:
<syntaxhighlight 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.
Line 1,921 ⟶ 1,919:
 
=={{header|Sidef}}==
<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 object at which the variable points to</syntaxhighlight>
Line 1,936 ⟶ 1,934:
You asked for it, and here it is:
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">|p|
p := Point x:10 y:20.
ObjectMemory addressOf:p.
Line 1,944 ⟶ 1,942:
For those, we can allocate a block of memory and fiddle around with its "address":
{{works with|Smalltalk/X}}{{works with|VisualWorks Smalltalk}}
<syntaxhighlight lang="smalltalk">|ptr|
ptr := ExternalBytes new:10.
ptr address.
Line 1,950 ⟶ 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:
<syntaxhighlight lang="text">|holder|
holder := ValueHolder with:123.
holder onChangeSend:#someChange to:someone.
Line 1,956 ⟶ 1,954:
</syntaxhighlight>
 
{{omit from|Smart BASIC}}
 
=={{header|Stata}}==
Line 1,962 ⟶ 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.
 
<syntaxhighlight lang="stata">a = 1
&a
 
Line 1,972 ⟶ 1,969:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
class MyClass { }
 
Line 2,022 ⟶ 2,019:
<br>
{{libheader|critcl}}
<syntaxhighlight lang="tcl">package require critcl
# This code assumes an ILP32 architecture, like classic x86 or VAX.
critcl::cproc peek {int addr} int {
Line 2,044 ⟶ 2,041:
package provide poker 1.0</syntaxhighlight>
Demonstrating:
<syntaxhighlight lang="tcl">package require poker
 
# Increment a memory location; this will probably crash if you try for real.
Line 2,068 ⟶ 2,065:
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.
 
<syntaxhighlight 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,117 ⟶ 2,113:
 
=={{header|Wart}}==
<syntaxhighlight lang="wart">addr.x
=> 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.
 
<syntaxhighlight lang="wart">if (addr.x = addr.y)
..</syntaxhighlight>
 
Line 2,133 ⟶ 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.
<syntaxhighlight lang="ecmascript">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,150 ⟶ 2,146:
=={{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.)
<syntaxhighlight lang=Assembler"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.
 
<syntaxhighlight lang=Assembler"assembler"> call eip_to_eax
addl $_GLOBAL_OFFSET_TABLE_, %eax
movl my_variable@GOT(%eax), %eax
Line 2,164 ⟶ 2,160:
=={{header|XLISP}}==
To get the address in the heap of a variable <code>X</code>, use:
<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.
 
Line 2,178 ⟶ 2,174:
instead of a 32-bit relative address, when used on a 'real' variable.
 
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\codes;
int A, B;
[B:= addr A;
Line 2,214 ⟶ 2,210:
===Specifying a Memory Location===
Only the accumulator <code>A</code> can do this. If you want to store another 8-bit register's contents directly into memory, you'll need to load that register's contents into <code>A</code> first:
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
ld (foo),a ;store A into memory location &C000
Line 2,222 ⟶ 2,218:
===Using BC or DE===
Only the accumulator <code>A</code> can do this. If you want to store another 8-bit register's contents into the address pointed to by BC or DE, you'll need to load that register's contents into <code>A</code> first:
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
 
Line 2,233 ⟶ 2,229:
===Using HL===
The 8-bit registers <code>A,B,C,D,E</code> can all do this. H and L cannot, unless the value being stored happens to equal that "half" of the memory location.
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
ld hl,foo
Line 2,246 ⟶ 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.
 
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
 
Line 2,252 ⟶ 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.
<syntaxhighlight lang="z80">foo equ &C000
bar equ &C001
 
Line 2,259 ⟶ 2,255:
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
pub fn main() !void {
Line 2,269 ⟶ 2,265:
}</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|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|KE}}
{{omit from|Factor}}
{{omit from|Falcon|Falcon does not support direct access of variable pointers}}
Line 2,285 ⟶ 2,287:
{{omit from|GUISS}}
{{omit from|Haskell}}
{{omit from|EIcon}}
{{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|PlainTeX}}
{{omit from|PHP}}
{{omit from|PlainTeX}}
{{omit from|Scratch}}
{{omit from|Smart BASIC}}
{{omit from|TI-89 BASIC}}
{{omit from|TorqueScript}}
{{omit from|TPP}}
{{omit from|UNIX ShellUnicon}}
{{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}}
10,327

edits