Address of a variable

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

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

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

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

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


Get The Address

<lang ada>The_Address : System.Address; I : Integer; The_Address := I'Address;</lang>

Set The Address

Set the address of a variable to address A100 in hexadecimal <lang ada>I : Integer; for I'Address use 16#A100#;</lang> Set the address of one variable to the address of another variable, creating an overlay. <lang ada>I : Integer; J : Integer; for I'Address use J'Address;</lang>


Basically ALGOL 68 refuses to let the programmer access the memory directly. The language does allow "references" any variables. These references are effectively the address a particular variable. But the value of the actual address is not available for printing or any arithmetic. <lang algol68>[4]INT test := (222,444,666,888); REF INT reference := test[3]; REF INT(reference) := reference + 111; print(("test value is now: ",test))</lang>

test value is now:        +222       +444       +777       +888

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

To establish a channel with such a device there is a special standard procedure:<lang algol68>PROC establish = (REF FILE file, STRING idf, CHANNEL chan, INT p, l, c) INT: ~</lang> Where the idf string is text describing which device to open, and possibly options. And chan is the actual device type. Standard CHANNELs in ALGOL 68 are stand in channel, stand out channel, and stand back channel. These determine the type of the pre opened stdio FILEs stand in, stand out, and stand back. A site would be expected to implement their own CHANNELs for network connections, database queries and particle accelerators etc.


Get the address

Works with: Argile version 1.0.0

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

Set the address

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

Works with: Argile version 1.0.0

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


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 <lang AutoHotkey>msgbox % &var</lang>


Many BASICs, especially older flavors like QuickBASIC, lack the ability to set a variable's address (and indeed, they pretty much all lack the ability to work with pointers in any fashion). <lang qbasic>'get a variable's address: DIM x AS INTEGER, y AS LONG y = VARPTR(x)

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


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

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

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


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

Get the address

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

<lang csharp>unsafe {

 int i = 5;
 void* address_of_i = &i;


C / C++

Works with: gcc
Works with: g++

Get the address

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

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: <lang cpp>int& i = *(int*)0xA100;</lang>

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

 int i;
 int j;

};</lang> C++ only: An alternative (and cleaner) solution is to use references: <lang cpp>int i; int& j = i;</lang> Note that in this case, the variables can be non-static.


Pointers were added in COBOL 2002.

Get Address

<lang cobol>data division. working-storage section. 01 ptr usage pointer. 01 var pic x(64).

procedure division. set ptr to address of var.</lang>

Set Address

Sets the address of a variable using the BASED clause. There are other methods, in particular LINKAGE SECTION variables. <lang cobol> OCOBOL*> Rosetta Code set address example

     *> tectonics: cobc -x setaddr.cob && ./setaddr 
      program-id. setaddr.
      data division.
      working-storage section.
      01 prealloc  pic x(8) value 'somedata'.
      01 var       pic x(8) based.
      procedure division.
      set address of var to address of prealloc
      display var end-display
      end program setaddr.</lang>

Common Lisp

Simulated Address of Variable

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

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

<lang lisp>;;; Demonstration of references by swapping two variables using a function rather than a macro


(defun swap (ref-left ref-right)

 ;; without with-refs we would have to write this:
 ;; (psetf (deref ref-left) (deref ref-right)
 ;;        (deref ref-right) (deref ref-left))
 (with-refs ((l ref-left) (r ref-right))
   (psetf l r r l)))

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

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

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

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

Varible-Like Moniker for External Location

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

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

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

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

<lang lisp>(use-package :ffi)

(defmacro def-libc-call-out (name &rest args)

 `(def-call-out ,name
    (:language :stdc)
    #-cygwin(:library "")
    #+cygwin (:library "cygwin1.dll")


 (def-libc-call-out errno-location
   #-cygwin (:name "__errno_location")
   #+cygwin (:name "__errno")
   (:return-type (c-pointer int)))
 (defun get-errno ()
   (let ((loc (errno-location)))
     (foreign-value loc)))
 (defun set-errno (value)
   (let ((loc (errno-location)))
     (setf (foreign-value loc) value)))
 (defsetf get-errno set-errno)
 (define-symbol-macro errno (get-errno)))</lang>


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

Creative Basic

<lang Creative Basic>


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

DEF X:INT DEF pPointer:POINTER pPointer=X

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

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

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

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


'***Call function*** Ptr=Lstrcpy(X1,X1)


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

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





SUB MainHandler






Note: The Windows Dev Center ( says improper use of the Lstrcpy function may compromise security. A person is advised to see the Windows Dev site before using the Lstrcopy function.


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

DEF pMem as POINTER pMem = NEW(CHAR,1000) : 'Get 1000 bytes to play with

  1. <STRING>pMem = "Copy a string into memory"

pMem += 100

  1. <UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT

DELETE pMem </lang>

Component Pascal

BlackBox Component Builder <lang oberon2> MODULE AddressVar; IMPORT SYSTEM,StdLog;


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

BEGIN x := 10; END AddressVar. </lang> Execute: ^Q AddressVar.Do

ADR(x):> 653700D8H


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

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

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

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

<lang d>void test(ref int i) {



void main() {

   test(* (cast(int*)0xdeadf00d) );



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

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

   Int : integer ;
   p   : ^integer ;
   P := @int ;

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

   CrtMode : integer absolute $0040 ;
   Str     : string[100] ;
   StrLen  : byte absolute Str ;


ERRE hasn't pointers, but with a trick you can get the address of a variable <lang> ........ A=100 !$RCODE="ADDRESS=VARPTR(A)" ....... </lang> ADDRESS contains the value of variable A (a value from 0 to 65535 because every ERRE module has a 64K address space). ERRE data types is 2 bit-long for integer, 4 for reals and 8 for double-real variables.


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

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

   ReferenceOf a = b

whereby a is set to refer to the variable b.

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

   @a = @b

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

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

   SUB Foo()
       PRINT "foo"
   SUB Bar()
       PRINT "bar"
   Foo() // prints "bar" to the console

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


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

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

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

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


Works with: Fortran version 90 and later

<lang fortran>program test_loc

 implicit none
 integer :: i
 real :: r
 i = loc (r)
 write (*, '(i0)') i

end program test_loc</lang> Note: loc is a common extension that is implemented by e.g. the Intel Fortran Compiler, G95 and gfortran.


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

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

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

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

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

import ( "fmt" "unsafe" )

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

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

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


On a 32 bit architecture:

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

On a 64 bit architecture:

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


<lang IWBASIC>


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

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

The second is to use a pointer:

DEF X:INT DEF pPointer:POINTER pPointer=X

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


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

DEF pMem as POINTER pMem = NEW(CHAR,1000) : 'Get 1000 bytes to play with

  1. <STRING>pMem = "Copy a string into memory"

pMem += 100

  1. <UINT>pMem = 34234: 'Use bytes 100-103 to store a UINT

DELETE pMem </lang>


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)

  var_addr =: 15!:6<'var'       NB.  Get address
  new_var  =: 15!:7 var_addr    NB.  Set address</lang>


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


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

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

Another common use of pointers is for arrays of values, which are typically passed in low-level C-like libraries via pointers to contiguous sets of values in memory. This is accomplished in Julia by the pointer(A) function, which returns a pointer to the data stored in a high-level Julia array A. Given a pointer p to values of a given type, the i-th value (numbered starting at 1 for the value pointed to by p) can be read or written by the low-level unsafe_load(p, i) and unsafe_store!(p, val, i) functions, or it can be converted back to a high-level Julia array type by the pointer_to_array(p, dimensions) function:<lang julia>julia> A = [1, 2.3, 4] 3-element Array{Float64,1}: 1.0 2.3 4.0 julia> p = pointer(A) Ptr{Float64} @0x0000000113f70d60 julia> unsafe_load(p, 3) 4.0 julia> unsafe_store!(p, 3.14159, 3) julia> A 3-element Array{Float64,1}: 1.0 2.3 3.14149 julia> pointer_to_array(p, (3,)) 3-element Array{Float64,1}: 1.0 2.3 3.14149</lang> Finally, an arbitrary integer can be converted to a pointer type with convert, which allows an arbitrary address to be converted into and viewed as an array of an arbitrary type and read or written (although this can easily result in a crash if an invalid address is used). In the following example, we create a "new" length-two array B at an address offset by 8 bytes from the address of the data in A above, which will make it point to the second element of A:<lang julia>julia> julia> q = convert(Ptr{Float64}, 0x0000000113f70d68) Ptr{Float64} @0x0000000113f70d68 julia> B = pointer_to_array(q, (2,)) 2-element Array{Float64,1}: 2.3 3.14149</lang>


Get Address

<lang modula2>MODULE GetAddress;



       adr : LONGINT;


   adr := ADR(var);    (*get the address*)
   WriteInt(adr, 0);

END GetAddress.</lang>

Set Address

<lang modula2>MODULE SetAddress;

CONST adress = 134664460;

VAR var [adress] : INTEGER;


   (*do nothing*)

END SetAddress.</lang>


Get Address

<lang NewLISP> (set 'a '(1 2 3)) (address a) </lang>


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


Get Address


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

Set Address

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


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

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

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

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

<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 *)
   invalid_arg "Can only find address of boxed values.";;

let () =

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


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



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


int *aa,*bb,*cc

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

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


<lang Panoramic>




dim a print adr(a)


Whether Panoramic is able to set the value of a variable may depend on what is meant by that. Panoramic implements the poke command to set a byte from a value of 0 to 255 (inclusive). Panoramic also implements the peek command to get the value of a byte, so it is possible to the following:

(A) dim a rem a variable with no post-fix is a real. poke adr(a),57 rem the value of a variable being set by setting an address, the address of a in this instance.

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

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

rem Observations and further insight welcome.

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


In GP you can sent the address to built-in commands like issquare <lang parigp>issquare(n, &m)</lang> but you cannot directly compute with it. You can view the address of a variable and other debugging information with the



In PARI you can use standard C commands.


See Delphi


To get the address, get the reference to a variable, and either stringify it, or use Scalar::Util's refaddr() to get just the address. Also see Devel::Peek. <lang perl>use Scalar::Util qw(refaddr); print refaddr(\my $v), "\n"; # 135691508</lang> Use Devel::Pointer::PP if you want to dereference a certain address in memory.

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

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

Example how to make variable overlay. <lang perl>my $a = 12; our $b; # you can overlay only global variables (this line is only for strictness)

  • b = \$a;

print $b; # prints 12 $b++; print $a; # prints 13</lang>

Perl 6

<lang perl6>my $x; say $x.WHERE;</lang>


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


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

The returned address is a number representing an encoded pointer. For symbols, it is a negative number, and for cons pairs a positive number. The same function 'adr' can then be used to convert that pointer back to the original object. <lang PicoLisp>: (setq X 7) -> 7

(adr 'X)

-> -2985527269106

(val (adr -2985527269106))

-> 7

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

-> (a b c)


-> (a b c)</lang>


<lang PL/I> declare p pointer; k = addr(b); /* Obtain address of variable, stored in integer variable k */ p = addr(q); /* assigns address to pointer variable p. */ </lang>


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

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

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

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


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

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

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

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


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

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

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

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


<lang racket>#lang racket

(require ffi/unsafe)

(define (madness v) ; i'm so sorry

  (cast v _racket _gcpointer))</lang>

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

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


<lang vb> Dim TheAddress as long Dim SecVar as byte Dim MyVar as byte

   MyVar = 10

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

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

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

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

'SecVar is now also = 102 showmessage "SecVar = " + str$(SecVar) </lang>


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

Get The Address

<lang Retro>variable a &a</lang>

Set The Address

Create variable b and point it to address 100 <lang Retro>variable b 100 @last !d->xt</lang>

Byte Addressing

Retro includes a standard library allowing for creation and access of byte-level data. This is done by creating a pool, which the library functions can then access individual bytes from. The pool has a physical address, which can be set or read, and virtual addresses (starting with zero, and increasing linearly) which are used by the library functions.

To read the address of the currently active pool:

<lang Retro>needs bad' ^bad'pool @</lang>

Or to set the pool to a specific physical location such as address 100:

<lang Retro>100 ^bad'pool !</lang>


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

It is possible to use the BIF (shown below)  (at least, in the original REXX) <lang rexx>zzz = storage(xxx)</lang> (but only in some REXX interpreters)   to access the internal REXX pool of variables, but it
would depend on the (internal) REXX internal structure(s) and almost likely be not portable nor
useable across releases of REXX or the operating system.   It would be necessary to follow a
pretty complex chain of pointers to just find the REXX pool of variables and the internal structure
may be pretty complicated and somewhat obscure.   Going down this path is not for the faint of


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

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

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

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


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


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

You asked for it, and here it is:

Works with: Smalltalk/X

<lang smalltalk>|p| p := Point x:10 y:20. ObjectMemory addressOf:p. ObjectMemory collectGarbage. ObjectMemory addressOf:p</lang> to deal with non-Smalltalk objects, all Smalltalks provide libraries to pass-in and out parameters to foreign function calls (FFI). For those, we can allocate a block of memory and fidle around with its "address":

Works with: Smalltalk/X

<lang smalltalk>|ptr| ptr := ExternalBytes new:10. ptr address. ptr byteAt:1 put: 16rFF.</lang>


<lang swift>class MyClass { }

func printPointer<T>(ptr: UnsafePointer<T>) {



func test() {

 var x = 42
 var y = 3.14
 var z = "foo"
 var obj = MyClass()
 // Use a pointer to a variable on the stack and print its address
 withUnsafePointer(&x) { ptr in println(ptr) }
 withUnsafePointer(&y) { ptr in println(ptr) }
 withUnsafePointer(&z) { ptr in println(ptr) }
 withUnsafePointer(&obj) { ptr in println(ptr) }
 // Alternately:
 // Printing the address of an object that an object reference points to





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

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

Library: critcl

<lang tcl>package require critcl

  1. This code assumes an ILP32 architecture, like classic x86 or VAX.

critcl::cproc peek {int addr} int {

   union {
      int i;
      int *a;
   } u;
   u.i = addr;
   return *u.a;

} critcl::cproc poke {int addr int value} void {

   union {
       int i;
       int *a;
   } u;
   u.i = addr;
   *u.a = value;

} package provide poker 1.0</lang> Demonstrating: <lang tcl>package require poker

  1. Increment a memory location; this will probably crash if you try for real.
  2. We don't define how to get a good address, but it's not usually a problem
  3. for embedded programming...

set where 0x12340 poke $where [expr {[peek $where] + 1}]</lang> Have great care with this sort of code; the damage you can do by writing to random locations is considerable and being able to read from anywhere could allow information to flow to otherwise unauthorized programs.


Get the Address

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

variable foo
foo .

Set the Address

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

 hex abcdef is-data foo
 foo .

Visual Basic .NET

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

Get the Address

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

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

Set the Address

Sets the pointer to the address A100 in hex.

 Dim ptrX As New IntPtr(&HA100)


<lang wart>addr.x => 27975840</lang>

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

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


As a result, wart has only one way to compare values: two objects are equal if they look the same, if they are structurally isomorphic. (You can always override it if you want a different behavior.)


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

<lang XPL0>include c:\cxpl\codes; int A, B; [B:= addr A; HexOut(0, B); CrLf(0); B(0):= $1234ABCD; HexOut(0, A); CrLf(0); ]</lang>



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

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