Near Pointer
Compilers like Turbo C supports the following pointers.
1. near pointer
2. far pointer
3. huge pointer
Let us see more details on near pointer. Size of near pointer is 2 bytes and it can point to only 64 KB of memory.
2 bytes = 16 bits
2^16 = 65536 => 64KB
So, near pointer can refer any address from 0 to 65535 (ie) 0x0000 to 0xFFFF
Then, how near pointer can refer memory location beyond 65535th byte. In DOS environment, only 16 bit data bus(connects microprocessor and memory) and 20 bit address bus would be used.
16 bit data bus - Capable of transferring 16 bits of data at a time.
20 bit address bus - 2^20 => Capable of accessing 10,48,576 locations in memory.
1MB = 1024 KB
64KB X 16 = 1024KB
So, 1MB has sixteen 64KB data segments.
+------------+
| 64KB | Segment F(15)
+------------+
| 64KB | .
+------------+
| 64KB | .
+------------+
| 64KB | Segment 2
+------------+
| 64KB | Segment 1
+------------+
| 64KB | Segment 0
+------------+
Here, addresses in segment 0 are from 0th byte to 65535th byte. The memory locations in segment 0 can be accessed using near pointer. But, it cannot refer any address beyond 65535th byte. Because, the size of near pointer is only 16 bits(2 bytes). In order to access memory location beyond 65535th byte, near pointer uses data in 16 bit code/data segment register. And the near pointer contains the offset part. 65536th byte is present in segment 1. Hexa decimal format of 65536 is 0x10000.
Then, first four digits hexadecimal digits(ie) 0x1000(0x10000/0x10 = 0x1000)will be stored in code/data segment register. Whereas the offset 0x0 will be available in near pointer. The conjunction of data in data segment register and near pointer gives us access to memory location beyond 65535th byte.
#include <stdio.h>
int main() {
char near *ptr = 0x0000;
printf("Size of near pointer: %d\n", sizeof(ptr));
/* moving one byte ahead */
printf("ptr+1: 0x%04x\n", ptr + 1);
/* moving one byte backward */
printf("ptr-1: 0x%04x\n", ptr - 1);
return 0;
}
Output:
Size of near pointer: 2
ptr+1: 0x0001
ptr-1: 0xFFFF
The above program shows that the address referred by near pointer loops circularly from 0x0000 to 0xFFFF.
Comments
Post a Comment