Jump to content

Pointers and references: Difference between revisions

no edit summary
No edit summary
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]].
=={{header|6502 Assembly}}==
===Pointers===
In <code>C</code>, <code>8086 Assembly</code>, and <code>Z80 Assembly</code>, a number that is an operand in an instruction, such as <code>mov ax,3</code> or <code>int x = 3;</code>, is an <i>immediate number</i>, i.e. a constant that equals the value of that number. <code>6502 Assembly</code> is the opposite. A number <b>without</b> a # in front represents a memory address.
 
<lang 6502asm>LDA $19 ;load the value at memory address $19 into the accumulator
LDA #$19 ;load the value hexadecimal 19 (decimal 25) into the accumulator</lang>
 
As you can see, the pointer is dereferenced automatically. The 6502 only has 8-bit registers and all memory addresses are 16-bit, so we can't do pointer arithmetic in the same way we could on the z80 for example. (If a one-byte address is specified as an operand, that is just the low byte; the high byte is assumed to equal 00 if none is given.) Rather, the x and y registers are used for offsetting.
 
<lang 6502asm>LDX #$05
LDA $2000,x ;load into the accumulator the byte stored at memory address $2005</lang>
 
The above example also works with y.
 
===Double Pointers===
A pointer to a pointer is a little complicated on the 6502. First of all, this is a little-endian processor, so the bytes get swapped. Second, you HAVE to use X or Y. If you don't want to use X or Y to offset, set them to zero before the lookup. Unlike the above example, x and y work differently.
 
<lang 6502>LDA #$30
STA $2000
LDA #$50
STA $2001
 
LDA #$80
STA $2005
LDA #$90
STA $2006
 
 
LDX #$05
LDY #$07
 
LDA ($2000),y ;the values of $2000 and $2001 are looked up and swapped (this is a little-endian cpu after all)
;and the value at (that address plus Y) is loaded. In this example, this equates to LDA $5037
LDA ($2000,x) ;x is added to $2000 and the values at that address and the one after are looked up and swapped, and the
;value at the resulting address is loaded. In this example, this equates to LDA $9080</lang>
 
 
 
=={{header|8086 Assembly}}==
===Pointers===
1,489

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.