Saturday, December 10, 2011

keil C Programming Tutorial: Pointers

►Pointers in Keil C

Pointers in keil C is are similar to that of standard C and can perform all the operations that are available in standard C. In addition, keil C extends the operatability of pointers to match with the 8051 Controller architecture. Keil C provides two different types of pointers:

  1. Generic Pointers
  2. Memory-Specific Pointers



►Generic Pointers:
Generic Pointers are declared same as standard C Pointers as shown below:

CODE:
char *ptr;      //Character Pointer
int *num;       //Integer Pointer

Generic pointers are always stored using three bytes. The first byte is the memory type, the second byte is the high-order byte of the offset, and the third byte is the low-order byte of the offset. Generic pointers maybe used to access any variable regardless of its location.


►Memory-Specific Pointers:
Memory specific pointers are defined along with memory type to which the pointer refers to, for example:

CODE:
char data *c;
//Pointer to character stored in Data memory

char xdata *c1;
//Pointer to character stored in External Data Memory.

char code *c2;
//Pointer to character stored in Code memory

As Memory-Specific pointers are defined with a memory type at compile time, so memory type byte as required for generic pointers is not needed. Memory-Specific pointers can be stored using 1 byte (for idata, data, bdata and pdata pointers) or 2 bytes (for code and xdata pointers).


The Code generated by keil C compiler for memory-specific pointer executes more quickly than the equivalent code generated for a generic pointer. This is because the memory area accessed by the pointer is known at the compile time rather at run-time. The compiler can use this information to optimize memory access. So If execution speed is your priority then it is recommended to use memory-specific pointers.


Generic pointers and Memory-Specific pointers can be declared with memory area in which they are to be stored. For example:

CODE:
//Generic Pointer
char * idata ptr; //character pointer stored in data memory
int * xdata ptr1; //Integer pointer stored in external data memory

//Memory Specific pointer
char idata * xdata ptr2; //Pointer to character stored in Internal Data memory
//and pointer is going to be stored in External data memory
int xdata * data ptr3; //Pointer to character stored in External Data memory
//and pointer is going to be stored in data memory

No comments:

Post a Comment