Why Pointers are 3 Bytes in Embedded C
Understanding Why Pointers are 3 Bytes in Embedded C
In Embedded C, a "ptr" data type is used to declare a pointer variable. The size of a pointer variable depends on the architecture of the microcontroller and the compiler being used.
In some cases, the pointer data type may be 3 bytes in size instead of the typical 2 or 4 bytes. This is because some microcontrollers use a segmented memory architecture, where the memory is divided into multiple segments, each with a maximum size of 64 KB.
To access a location in memory that is beyond the current segment, the microcontroller requires a segment address and an offset address. The 3-byte pointer data type includes both the segment address and the offset address, allowing the program to access any location in memory.
Here's an example of how to use the 3-byte "ptr" data type in Embedded C:
#include
// Declare a 3-byte pointer variable
typedef unsigned char uchar;
typedef unsigned int uint;
typedef union {
uchar _far * cptr;
uint _far * iptr;
} PTR;
PTR xdata p;
void main(void) {
uchar xdata * ptr1;
uint xdata * ptr2;
// Set the pointer to a location in memory
p.cptr = 0x8000;
// Access the value at the pointer location
*p.cptr = 0xAA;
// Move the pointer to another location
p.iptr++;
// Access the value at the new pointer location
*p.iptr = 0x1234;
}
Conclusion
In this example, we declare a 3-byte pointer variable named "p" using a union to store both the segment address and the offset address. We use the "p" pointer variable to access and manipulate values in memory, and we move the pointer to a different location using pointer arithmetic.
Note that the specific syntax and usage of the 3-byte "ptr" data type may vary depending on the microcontroller and compiler being used. It is important to refer to the microcontroller's datasheet and programming guide to determine the correct usage and syntax for a given application.