Example: Observing the Contents of Memory by ubyte*

Let’s look at another example to understand pointers in D.

We'll cover the following

The data stored at each memory address is a byte. Every variable is constructed on a piece of memory that consists of as many bytes as the size of the type of that variable.

A suitable pointer type to observe the content of a memory location is ubyte*. Once the address of a variable is assigned to a ubyte pointer, all of the bytes of that variable can be observed by incrementing the pointer.

Example

Let’s consider the following integer, which is initialized by the hexadecimal notation so that it will be easy to understand how its bytes are placed in memory:

int variable = 0x01_02_03_04;

A pointer that points at that variable can be defined like this:

int * address = &variable;

The value of that pointer can be assigned to a ubyte pointer by the cast operator:

ubyte * bytePointer = cast(ubyte*)address;

Such a pointer allows accessing the four bytes of the int variable individually:

writeln(bytePointer[0]);
writeln(bytePointer[1]);
writeln(bytePointer[2]);
writeln(bytePointer[3]);

Get hands-on with 1200+ tech skills courses.