Address of a variable: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
(→‎[[Delphi / Object pascal / Turbo Pascal]]: Changed section title to point to correct page)
Line 38: Line 38:
Note that in this case, the variables can be non-static.
Note that in this case, the variables can be non-static.


==[[Delphi / Object pascal / Turbo Pascal]]==
==[[Delphi]]==
[[Category:Delphi]]
[[Category:Delphi]]
'''Compiler:''' [[ALL]]
'''Compiler:''' [[ALL]]

Revision as of 14:03, 21 March 2007

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

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

Ada

Get The Address

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

Set The Address

Set the address of a variable to address A100 in hexidecimal

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

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

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

C++

Compiler: GCC

Get the address

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

int i;
void* address_of_i = &i;

Set the address

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

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

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

static union
{
  int i;
  int j;
};

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

int i;
int& j = i;

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

Delphi

Compiler: ALL

Pascal supports the @ ( address of ) operator and the var : [type] absolute declaration.

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

 var
   Int : integer ;
   p   : pointer ;
 begin
   P := @int ;
   writeln(integer(p^));
 end;

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

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