...

/

Assigning Numbers to Memory Using Pointers

Assigning Numbers to Memory Using Pointers

Learn how to assign numbers to memory locations using pointers.

Pointers to assign numbers

The following sequence of pseudocode instructions means that we interpret the contents of the x0 register as the address of a memory cell and then assign a value to that memory cell:

Press + to interact
x0 <- address a
[x0] <- 1

In the C/C++ language

In C and C++, it is called dereferencing a pointer:

Press + to interact
int a;
int *pa = &a; // declaration and definition of a pointer
*pa = 1; // get a memory cell (dereference a pointer)
// and assign a value to it

In the assembly language

In the assembly language, we write the following:

Press + to interact
adr x0, a // load the address “a” into x0
mov w3, #1 // set the temporary register to 1
str w3, [x0] // use x0 as a pointer and store 1 at the memory address in x0

In GDB disassembly output

In the GDB disassembly output, we see something like this:

Press + to interact
0x00000000004000b0 <+0>: adr x0, 0x4100f0
0x00000000004000b4 <+4>: mov w3, #0x1
0x00000000004000b8 <+8>: str w3, [x0]

Explanation

To illustrate some instructions and not to be dependent on how the compiler translates C/C++ code, we wrote the program in the assembly language.

Source code

The source code of the pointers is given below:

Press + to interact
.data
a: .word 0
b: .word 0
.text
.global _start
main:
_start:
adr x0, a
mov w3, #1
str w3, [x0]
adr x1, b
str w3, [x1]
ldr w2, [x0]
ldr w3, [x1]
add w4, w3, w2
str w4, [x1]
add w2, w2, #1
str w2, [x0]
mul w3, w4, w2
str w3, [x1]
mov x0, #0
mov w8, #93
svc #0

Here is a breakdown of the code presented above:

  • Lines 1–11: These are the header commands of the assembly code.
  • Line 12: We load the address of a and store it in x0 register.
  • Line 13: We assign #1 to the register w3.
  • Line 14: Then, we store the value from register w3 and assign it to the address pointed by x0.
  • Line 16: We load the address of b and store it in x1 register.
  • Line 17: We store the value from register w3 and assign it to the address in x1.
  • Line 19: We load the value in [x0] and store it in the w2 register.
  • Line 20: We load the value in [x1] and store it in the w3 register.
  • Line 21
...