Pages1

Interacting with memory locations directly using C pointer


The real power of  “C” comes from the fact the one can directly access memory location( Port, registers of peripheral etc.) using pointer. Below is the example to perform this operation:

Int *pPort;                      /* Pointer Declaration; Pointer allocated, pointing to some unknown location */
pPort = ( Int *)0x4000; /* Pointer Initialization to valid and known address 
                                         Typecasting is used */
*pPort = 0xAA55;       /* Value written on location pointed by pointer pPort */

Optionally one can rewrite same in below fashion; But it is always advisable to use readable format.

*( Int *const)(0x4000) = 0xaa55;

Why typecasting is required?
Typecasting is required to explicitly convert one data type to other. It instructs program to read a integer value from port in case of “pPort = ( Int *)0x4000;”
To read character data type we changes like  “pPort = ( char *)0x4000;” then underlying program will expect a value which is “char”.



No comments:

Post a Comment