C++: Address of a Variable


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;

C++ only: 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.


Content is available under GNU Free Documentation License 1.2.