Keil Logo

C51: Accessing a Pointer in Assembler


Information in this article applies to:

  • C51 version 5.50 and later

QUESTION

I have a pointer declared in C that I wish to manipulate in assembler. How do I do it?

ANSWER

The best way is to write what you want to do in C then and then use the compiler SRC directive to generate the equivalent assembler. For example, ptr is declared in C as:

unsigned char idata *ptr;

The following C code (using an idata pointer):

extern unsigned char idata *ptr;

void main(void)
{
  ptr = 0xA5;
  *ptr = 0x41;
}

generates the following assembler:

; ptr = 0xA5;
MOV     ptr,#0A5H
; *ptr = 0x41;
MOV     R0,ptr
MOV     @R0,#041H

The address is located in memory where the pointer lives and the value 41H is stored indirectly using that address.

The following C code (using an xdata pointer):

extern unsigned char xdata *ptr;

void main(void)
{
  ptr = 0xA5B6;
  *ptr = 0x41;
}

generates the following assembler:

; ptr = 0xA5B6;
MOV     ptr,#0A5H
MOV     ptr+01H,#0B6H
; *ptr = 0x41;
MOV     DPL,ptr+01H
MOV     DPH,ptr
MOV     A,#041H
MOVX    @DPTR,A

For generic pointer things get a little more complex. In order to use a generic pointer calls to library routines have to be made to load and store the pointer.

The following C code:

extern unsigned char *ptr;

void main(void)
{
  ptr = (unsigned char idata *)0xA5;
  *ptr = 0x41;
}

generates the following assembler:

; ptr = (unsigned char idata *)0xA5;
MOV     R3,#00H
MOV     R2,#00H
MOV     R1,#0A5H
MOV     ptr,R3
MOV     ptr+01H,R2
MOV     ptr+02H,R1
; *ptr = 0x41;
MOV     A,#041H
LCALL   ?C?CSTPTR

As you can see, the three bytes of the pointer (two for the address and one for the memory space) are placed in R1 to R3. These are then stored in memory where the pointer is located. The value 41H is placed in the Accumulator and the library routine ?C?CSTPTR is called to store the value.

Refer to C51: ?C? Load and Store Library Routines for more information on the library routines that are available. From this information you can manipulate pointers in assembler, however the best way to do this is to use the compiler SRC directive to write the assembler for you.

MORE INFORMATION

  • Refer to SRC in the Cx51 User's Guide.

SEE ALSO


Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.