Lab Exercise 11: Pointers and Pointer Arithmetic

Last modified by Microchip on 2023/11/09 09:21

Objective

This lab will serve as your first introduction to pointers. For many programmers, this is one of the more difficult concepts to grasp. The exercises presented here are by necessity very simplistic in order to help you get a firm grasp on the syntax associated with pointers. The application code presented here isn’t necessarily showing the best use of pointers, but it will clearly illustrate how they work, which will make it easier for you to implement them in more complex situations where they are most useful. So for the moment, if you can avoid the “why would anyone do this?” question, and focus on the syntax and mechanism of pointers, in the end you will be much better equipped to make use of them in your own code when they are required.

Reference Materials

Exercise Files

Back to Top


Procedure

Open the Project

Start MPLAB® X IDE, then click on the Open Project Main Open Project icon on the main toolbar

Navigate to the folder where you saved the exercise files for this class.

Click on the Lab11.X folder.

Select Open Project Open Project Button.

Back to Top


Open C Source File

Lab 11 C

Open the Lab11.c source file from the project tree by double clicking on its icon.

This will bring up Lab11.c in a window to edit

Back to Top


Edit Source File

Initialize the pointer p with the address of the variable x.
Hint: Use the unary & operator.

Complete the following printf() functions by adding in the appropriate arguments as described in the control string. NOTE: This program will not build unless the following 5 lines of code are completed and the comments are removed from within the printf() functions.

(1) Address of the variable x - use address of operator
(2) Value of the variable x
(3) Address of the pointer p itself (not what p points to) - use address of operator
(4) Value of the pointer p (address of what p points to)
(5) Value pointed to by p (value stored in location p points to) - dereference the pointer

Write the integer value 10 to the location that p points to. - dereference the pointer
Increment the value that p points to. - dereference the pointer

Increment the pointer p so that it points to the next item. Don’t forget operator precedence—use parentheses if necessary.

Lab 11 Flow

Back to Top


Debug Project

Once you finish writing the code:

Click on the Debug Project Main Debug Project button. This will build and send the program to the simulator.
Click on the Continue Debug Continue button. This begins the simulation.Wait for the UART 1 Output window to finish printing.
Click on the Halt Debug Pause button. This will stop execution so that we may examine the results.

Back to Top


Results

Lab 11 Results

After building and running your code, you should see the following results in the UART1 Output window:
(Note: Your results may be different)

Back to Top

Code Analysis

(NOTE: Line numbers correspond to those in the provided solution file.)

Lines 12-14
Here, three variables are created for you:

  • int x, an ordinary integer, which is initialized with a value of 5. This variable will be assigned a location in RAM.
  • int y[10], an array of integers, initialized with values from 0 to 9. This variable will be assigned to a series of 10 sequential locations in RAM.
  • int *p, a pointer to an integer. The variable p will be assigned an address in RAM, and at that address, it will store the address of whatever variable it points to. p is not initialized, so for the moment, it has a value of NULL (i.e. its value is zero).

Line 30
A local variable (local to main() ) is declared. We will use this variable as a counter in the for loop.

Line 37
STEP 1:
Here, you were instructed to assign the address of x to the pointer to p. This is done by setting the variable p, equal to the address of x, using the address of ‘&’ operator:

p = &x;

Because we are writing the address of a variable into the pointer, we simply use the variable p, since that is where the address will be stored (no * is used in this case). In other words, the address of x is stored at the address of p.

Lines 44-48
STEP 2:
Here you were instructed to complete the printf() functions, based on the text description in their control strings.
(1) To complete this line, we need to refer to the address of the variable x, this is done just like we did on line 59 by using the address of operator:

printf(“The variable x is located at the address 0x%X\n”, &x);

(2) For this line, we need to refer to the value of the variable x. This is done by simply using the variable x by itself:

printf(“The value of x is 0x%X\n”, x);

(3) Now, we are going to work with the pointer variable. The intention of this line is to print out the address of the pointer variable p itself. This can be done the same way as we referred to the address of x:

printf(“The pointer p is located at address 0x%X\n”, &p);

(4) Next, we need to print out the value contained in p. This is the address of the object that p points to. To refer to a pointer’s value, you just use the pointer variable by itself, just like we did for x:

printf(“The value of p is 0x%X\n”, p);

(5) Finally, we are asked to print the value pointed to by p. To do this, we need to use the dereference operator ‘*’ with the pointer p (the control string provided a hint):

printf(“The value pointed to by *p is 0x%X\n”, *p);

The dereference operator allows us to retrieve whatever value is at the location that p is pointing to.

Line 55
STEP 3:
On this line, you were instructed to write the value 10 to the location pointed to by p. To do this, we need to use the dereference operator as we did in the last part of the previous step:

*p = 10;

Line 60
STEP 3:
Here, we reassign the pointer to point to the first element of the array y[]. We can do this because the only requirement for p is that it points to an integer. Since the elements of y[] are all integers, it is just as valid to have p point to one of y[]’s elements as it is to have it point to x.

Line 71
STEP 4:
We are now inside the for loop, where we will go through every element of the array y[] and print out its value. Instead of using the loop counter as the array index and using normal array notation to do this, we are going to use a pointer to iterate through each element of the array. This is a great illustration of the fact that arrays are merely simplified notation for pointers. Our first task is to increment the value that p points to. Due to operator precedence rules, we need to use parentheses to make this work properly:

(*p)++;

This syntax means that we first dereference the pointer, then perform the increment, so that the item pointed to by p is what gets acted on by the increment operator.

Line 72
STEP 4:
This line simply prints out the value contained in the array element that is currently pointed to by p. Note the use of the *p as the item in the argument list.

Line 78
STEP 5:
Now, we need to increment the pointer itself. To do this, we simply operate on the pointer variable itself:

p++;

Because of the way the compiler handles pointer arithmetic, this operation may or may not increment the value in p by 1. In this particular situation, where the 16-bit PIC® MCUs have byte addressable data memory, the value in p will actually be incremented by 2 since integer type variables occupy two bytes.


End Debug Session

End the Simulation Session by clicking the Finish Debugger Session Debug Finish Debugger Session button.

Clear out the UART 1 Output window (Ctrl + L).

Close the Project.


Back to Top

Conclusions

While this code doesn’t perform any particularly useful tasks, it does illustrate the functionality of the pointer mechanism in C. The main idea was for you to understand what syntax to use in which situations. Hopefully, this simple example made it easy to see what specifically is going on with all the ways you can work with pointers and variable addresses. From this you should have learned that everything, including pointers themselves have an address, and that a pointer of a particular type can point to anything of that same type, whether it be an individual variable or an array. Similarly, you should now see that pointers and arrays are very closely related, but that pointers are much more flexible, though they have a more complicated syntax. It should also be noted that pointers are one of the more difficult concepts to grasp in C, and that as a result, most programming errors are due to inappropriate use of pointers. So, the better you understand this section, the better C programmer you will be.

Back to Top