...
/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 x0mov w3, #1 // set the temporary register to 1str 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, 0x4100f00x00000000004000b4 <+4>: mov w3, #0x10x00000000004000b8 <+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
.dataa: .word 0b: .word 0.text.global _startmain:_start:adr x0, amov w3, #1str w3, [x0]adr x1, bstr w3, [x1]ldr w2, [x0]ldr w3, [x1]add w4, w3, w2str w4, [x1]add w2, w2, #1str w2, [x0]mul w3, w4, w2str w3, [x1]mov x0, #0mov w8, #93svc #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 inx0
register. - Line 13: We assign
#1
to the registerw3
. - Line 14: Then, we store the value from register
w3
and assign it to the address pointed byx0
. - Line 16: We load the address of
b
and store it inx1
register. - Line 17: We store the value from register
w3
and assign it to the address inx1
. - Line 19: We load the value in
[x0]
and store it in thew2
register. - Line 20: We load the value in
[x1]
and store it in thew3
register. - Line 21