Pointers and references: Difference between revisions

Content added Content deleted
Line 1: Line 1:
{{Task|Basic Data Operations}}{{basic data operation}}In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with [[Memory allocation]] on the [[heap]].
{{Task|Basic Data Operations}}{{basic data operation}}In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with [[Memory allocation]] on the [[heap]].
=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
===Pointers===
In most assemblers, an instruction or a numeric value can be given a label.
In most assemblers, an instruction or a numeric value can be given a label.
<lang asm>.model small
<lang asm>.model small
Line 42: Line 43:
Then this pointer can be loaded into a segment register and data register with a single command, like so:
Then this pointer can be loaded into a segment register and data register with a single command, like so:
<lang asm>LDS bx,UserRamPtr ;loads [ds:bx] with UserRamPtr</lang>
<lang asm>LDS bx,UserRamPtr ;loads [ds:bx] with UserRamPtr</lang>

===Pointer Arithmetic===

A pointer can be loaded into a register like any other value.
<lang asm>
.data
myString db "Hello World!",0 ;the zero is the null terminator
.code
mov bx, seg myString ;load into bx the segment where myString is stored.
mov ds, bx ;load this segment into the data segment register. On the 8086, segment registers can't be loaded directly.
mov bx, offset MyString ;the memory address of the beginning of myString. The "H" is stored here.</lang>

Once we have the pointer to myString in bx, we can perform arithmetic on it like it was an ordinary numerical value. There is no distinction between pointer arithmetic and normal arithmetic in assembly. All arithmetic commands are available for use. If the programmer wishes to use that memory address as a number for some other purpose, that is perfectly legal. However this example will stick to the "proper" uses of pointer arithmetic, i.e. indexing and offsetting.
<lang asm> add bx, 2 ;add 2 to bx. bx contains the memory address of the first "l" in "Hello"
mov al,[ds:bx] ;dereference the pointer and store the value it points to into al.</lang>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==