Lecture4 Pointer&array
Lecture4 Pointer&array
Page 1
CSC2302 Department of Mathematics and Computer Science
You now see that you can reference an array with subscripts or with pointer dereferencing. Can you use
pointer notation to print the third element of ara? Yes, and you already have the tools to do so. The
following cout prints ara[2] (the third element of ara without using a subscript:
cout << *(ara+2) ; // Prints ara[2].
The expression *(ara+2) is not vague at all, if you remember that an array name is just a pointer that
always points to the array’s first element. *(ara+2) takes the address stored in ara, adds two to the
address, and dereferences that location. The following holds true:
ara+0 points to ara[0]
ara+1 points to ara[1]
ara+2 points to ara[2]
ara+3 points to ara[3]
ara+4 points to ara[4]
Therefore, to print, store, or calculate with an array element, you can use either the subscript notation
or the pointer notation. Because an array name contains the address of the array’s first element, you
must dereference the pointer to get the element’s value.
Pointer Advantages
Although arrays are actually pointers in disguise, they are special types of pointers. An array name is a
pointer constant, not a pointer variable. You cannot change the value of an array name, because you
cannot change constants. This explains why you cannot assign an array new value during a program’s
execution. For instance, even if cname is a character array, the following is not valid in C++:
cname = “Christine Chambers”; // Invalid array assignment.
The array name, cname, cannot be changed because it is a constant. You would not attempt the
following
5 = 4 + 8 * 21; // Invalid assignment
Page 2
CSC2302 Department of Mathematics and Computer Science
Because you cannot change the constant 5 to any other value. C++ knows that you cannot assign
anything to 5, and C++ prints an error message if you attempt to change 5. C++ also knows an array
name is a constant and you cannot change an array to another value. (You can assign values to an array
only at declaration time, one element at a time during execution, or by using functions such as strcpy().)
This brings you to the most important reason to learn pointers:
pointers (except arrays referenced as pointers) are variables. You can change a pointer variable, and
being able to do so makes processing virtually any data, including arrays, much more powerful and
flexible.
Examples
1. By changing pointers, you make them point to different values in memory. The following program
demonstrates how to change pointers. The program first defines two floating-point values. A floating-
point pointer points to the first variable, v1, and is used in the cout. The pointer is then changed so it
points to the second floating-point variable, v2.
// Changes the value of a pointer variable.
#include <iostream.h>
#include <iomanip.h>
void main()
{
float v1=676.54; // Defines two
float v2=900.18; // floating-point variables.
float * p_v; / Defines a floating-point pointer.
p_v = &v1; // Makes pointer point to v1.
cout << “The first value is “ << setprecision(2) << *p_v << “\n”; // Prints 676.54.
p_v = &v2; // Changes the pointer so it points to v2.
cout << “The second value is “ << setprecision(2) <<*p_v << “\n”; // Prints 900.18.
return;
}
Because they can change pointers, most C++ programmers use pointers rather than arrays. Because
arrays are easy to declare, C++ programmers sometimes declare arrays and then use pointers to
reference those arrays. If the array data changes, the pointer helps to change it.
2. You can use pointer notation and reference pointers as arrays with array notation. The following
program declares an integer array and an integer pointer that points to the start of the array. The array
Page 3
CSC2302 Department of Mathematics and Computer Science
and pointer values are printed using subscript notation. Afterwards, the program uses array notation to
print the array and pointer values.
Study this program carefully. You see the inner workings of arrays and pointer notation.
// References arrays like pointers and
// pointers like arrays.
#include <iostream.h>
void main()
{
int ctr;
int iara[5] = {10, 20, 30, 40, 50};
int *iptr;
iptr = iara; // Make iptr point to array’s first
// element. This would work also:
// iptr = &iara[0];
cout << “Using array subscripts:\n”;
cout << “iara\tiptr\n”;
for (ctr=0; ctr<5; ctr++)
{ cout << iara[ctr] << “\t” << iptr[ctr] << “\n”; }
cout << “\nUsing pointer notation:\n”;
cout << “iara\tiptr\n”;
for (ctr=0; ctr<5; ctr++)
{ cout << *(iara+ctr) << “\t” << *(iptr+ctr) << “\n”; }
return;
}
Using Character Pointers
The ability to change pointers is best seen when working with character strings in memory. You can
store strings in character arrays, or point to them with character pointers. Consider the following two
string definitions:
char cara[] = “C++ is fun”; // An array holding a string
char *cptr = “C++ By Example”; // A pointer to the string
Figure 27.2 shows how C++ stores these two strings in memory. C++ stores both in basically the same
way. You are familiar with the array definition. When assigning a string to a character pointer, C++ finds
Page 4
CSC2302 Department of Mathematics and Computer Science
enough free memory to hold the string and assign the address of the first character to the pointer. The
previous two string definition statements do almost exactly the same thing; the only difference between
them is that the two pointers can easily be exchanged (the array name and the character pointers).
Because cout prints strings starting at the array or pointer name until the null zero is reached, you can
print each of these strings with the following cout statements:
cout << “String 1: “ << cara << “\n”;
cout << “String 2: “ << cptr << “\n”;
You print strings in arrays and pointed-to strings the same way. You might wonder what advantage one
method of storing strings has over the other. The seemingly minor difference between these stored
strings makes a big difference when you change them.
Suppose you want to store the string Hello in the two strings.
You cannot assign the string to the array like this:
cara = “Hello”; // Invalid
Because you cannot change the array name, you cannot assign it a new value. The only way to change
the contents of the array is by assigning the array characters from the string an element at a time, or by
using a built-in function such as strcpy(). You can, however, make the character array point to the new
string like this:
cptr = “Hello”; // Change the pointer so
// it points to the new string.
Examples
1. Suppose you want to store your sister’s full name and print it. Rather than using arrays, you can use a
character pointer. The following program does just that.
// Stores a name in a character pointer.
#include <iostream.h>
void main()
{
char *c=”Bettye Lou Horn”;
cout << “My sister’s name is “ << c << “\n”;
return;
}
2. Suppose you must change a string pointed to by a character pointer. If your sister changed her last
name to Henderson, your program can show both strings in the following manner:
Page 5
CSC2302 Department of Mathematics and Computer Science
Identify the program and include the I/O header file. This program uses a character pointer, c, to point
to a string literal in memory.
Point to the string literal, and print the string. Make the character pointer point to a new string literal,
then print the new string.
// Illustrates changing a character string.
#include <iostream.h>
void main()
{
char *c=”Bettye Lou Horn”;
cout << “My sister’s maiden name was “ << c << “\n”;
c = “Bettye Lou Henderson”; // Assigns new string to c.
cout << “My sister’s married name is “ << c << “\n”;
return;
}
3. Do not use character pointers to change string constants. Doing so can confuse the compiler, and you
probably will not get the results you expect. The following program is similar to those you just saw.
Rather than making the character pointer point to a new string, this example attempts to change the
contents of the original string.
// Illustrates changing a character string improperly.
#include <iostream.h>
void main()
{
char *c=”Bettye Lou Horn”;
cout << “My sister’s maiden name was “ << c << “\n”;
c += 11; // Makes c point to the last name
// (the twelfth character).
c = “Henderson”; // Assigns a new string to c.
cout << “My sister’s married name is “ << c << “\n”;
return;
}
The program seems to change the last name from Horn to Henderson, but it does not. Here is the
output of this program:
Page 6
CSC2302 Department of Mathematics and Computer Science
Page 7
CSC2302 Department of Mathematics and Computer Science
You saw an example of pointer arithmetic when you accessed array elements with pointer notation. By
now you should be comfortable with the fact that both of these array or pointer references are
identical:
ara[sub] and *(ara + sub)
You can increment or decrement a pointer. If you increment a pointer, the address inside the pointer
variable increments. The pointer does not always increment by one, however.
Suppose f_ptr is a floating-point pointer indexing the first element of an array of floating-point numbers.
You could initialize f_ptr as follows:
float fara[] = {100.5, 201.45, 321.54, 389.76, 691.34};
f_ptr = fara;
If you print the value of *f_ptr, you see 100.5. Suppose you increment f_ptr by one with the following
statement:
f_ptr++;
C++ does not add one to the address in f_ptr, even though it seems as though one should be added. In
this case, because floating point values take four bytes each on this machine, C++ adds four to f_ptr.
How does C++ know how many bytes to add to f_ptr? C++ knows from the pointer’s declaration how
many bytes of memory pointers take. This is why you have to declare the pointer with the correct data
type.
After incrementing f_ptr, if you were to print *f_ptr, you would see 201.45, the second element in the
array. If C++ added only one to the address in f_ptr, f_ptr would point only to the second byte, 100.5.
Examples
1. The following program defines an array with five values. An integer pointer is then initialized to point
to the first element in the array. The rest of the program prints the dereferenced value of the pointer,
then increments the pointer so it points to the next integer in the array.
Just to show you what is going on, the size of integer values is printed at the bottom of the program.
Because (in this case) integers take two bytes, C++ increments the pointer by two so it points to the next
integer. (The integers are two bytes apart from each other.)
// Increments a pointer through an integer array.
#include <iostream.h>
void main()
{
int iara[] = {10,20,30,40,50};
Page 8
CSC2302 Department of Mathematics and Computer Science
Page 9
CSC2302 Department of Mathematics and Computer Science
Page 10
CSC2302 Department of Mathematics and Computer Science
// 100.0 100.0
cout << (fptr+1)[0] << “ “ << (ara+1)[0] << “\n”;
// 200.0 200.0
cout << (fptr+4)[0] << “ “ << (ara+4)[0] << “\n”;
// 500.0 500.0
return;
}
Page 11