Understandig the use of pointers in C18

C18 compiler permits the use of pointers to handle arrays in FLASH memory of the microcontroller, when this array is passed to a function as a parameter.

For a better understanding of the use of pointers, using the simulator of MPLAB IDE will clarify things.

The test program shown in the left image, defines first a 5 element array in ROM called "arrayrom". Then defines an array in ram called "arrayram". The program uses a function called "transfer( )" to write each of the elements of the array in ROM to the array in RAM

Please observe how the array is passed as a pointer called *p to the function. Then, inside the function, the pointer is used to address each of the elements of the array in ROM. 



Source file of this program is: C18-BOLT-HANDLING-POINTERS-MPLAB-SIMULATION.c

Once you have created your C18 project in MPLAB IDE (include the source file and the linker script), enable the simulator with options: >Debugger>Select Tool>MPLAB SIM

Next, compile the program. Then configure the watch window: >View>Watch. Choose and add the variables you want to see during the simulation: "arrayrom", "arrayram", "p" and "a". You may also see each of the 5 elements of the chosen arrays, as shown in the window below.

Set breakpoints with 2 clicks in lines: b=0 and for(;;). Breakpoints appear as red hexagons. Initiate the simulation clicking the "Run" option in the simulator menu. The simulation will stop in the first breakpoint, showing a green arrow. Continue to click "Run" and you will see in the watch window how each element of the array in ROM is passed one by one to the array in RAM.

Note: line b=0 in the program is a dummy expression used only to set a breakpoint there and facilitate de simulation.

Please observe in the watch window how the pointer was created in address 240H (RAM), and that the contents of this address is 9AEH, that is, pointing to the first element of the array in ROM. Using a subindex, we may then address each of the elements through the expression: *(p+a).

Once the 5 elements of the ROM array were transfered to the RAM array, the simulation is finished when the green arrow gets to the second breakpoint in line for(;;) of program.

If you want to simulate the program again you must first erase the RAM memory. Use >Debugger>Clear Memory>All memory.  You must then recompile and repeat the procedure described above.