An array is a list or holding tank for a set of values.
Once those values are set it's very hard to re-order
them or add new items. However, we can use an array of pointers instead. This lesson will cover the
concept of using pointers in an array and provide working code examples.
Review of Arrays
Let's take a moment before we start in earnest on this lesson to recap the important
information about arrays. An array is a single element with multiple components. Think of it as
a list of names, phone numbers, or other information. You can think of each item in the list as a
bucket within that list. Remember, an array's buckets start counting with zero! Therefore, the
first bucket of any array is 0, the second 1, and so forth.
Here's a basic integer array:
1. #include <stdio.h>
2. #include <iostream>
3. using namespace std;
4. const in MAXIMUM = 5;
5. int main() {
6. int var[MAXIMUM] = {3, 18, 12, 32, 16)};
7. for(int i = 0; i < MAXIMUM; i++) {
8. cout << "Variable[" << i << "] = "
9. cout << var[i] << endl;
10. }
11. return 0;
12. }
The output would look like:
This type of array is common, and it works well in many situations. However, once the array is
set, it's very difficult to change. What if you want to add new values to the array, or switch the
order? It requires a lot of additional programming and frustration because of the way the array
has been written. What's the solution? Create an array of pointers. They point to the items in
the array. Then all we have to do is switch, add, change, modify the pointers!
Array of Pointers
A pointer holds an address to something. It's kind of like an address because it points to a
specific value. Check out the following diagram showing a pointer payCode pointing to a value
of 507.
To declare a pointer, we use the asterisk in front of the variable name, like the following:
1. int *ptr[MAXIMUM];
Before we look at a re-do of the prior code, we need to take a closer look at how we're working
with the pointers and the addresses. When we process the array, there's an extra line of code
that assigns the address/pointer to our original variable. Omitting this step is the most common
error in pointer code.
ptr[i] = &myvar[i];