0% found this document useful (0 votes)
13 views11 pages

Lecture4 Pointer&array

This document discusses pointers and arrays in C++. It begins by explaining that array names are pointers, and that arrays and pointers can be used interchangeably. It then provides examples of using arrays with subscript notation and pointer notation. The document also discusses using character pointers to store and manipulate strings. Key points are that arrays are constant pointers, while regular pointers can be changed to point to different locations, allowing for more flexibility when processing data.

Uploaded by

nuraddeen212
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
13 views11 pages

Lecture4 Pointer&array

This document discusses pointers and arrays in C++. It begins by explaining that array names are pointers, and that arrays and pointers can be used interchangeably. It then provides examples of using arrays with subscript notation and pointer notation. The document also discusses using character pointers to store and manipulate strings. Key points are that arrays are constant pointers, while regular pointers can be changed to point to different locations, allowing for more flexibility when processing data.

Uploaded by

nuraddeen212
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

CSC2302 Department of Mathematics and Computer Science

Pointers and Arrays


Arrays and pointers are closely related in the C++ programming language. You can address arrays as if
they were pointers and address pointers as if they were arrays. Being able to store and access pointers
and arrays gives you the ability to store strings of data in array elements. Without pointers, you could
not store strings of data in arrays because there is no fundamental string data type in C++ (no string
variables, only string literals).
This chapter introduces the following concepts:
 Array names and pointers
 Character pointers
 Pointer arithmetic
 Ragged-edge arrays of string data
This section introduces concepts you will use for much of your future programming in C++. Pointer
manipulation is important to the C++ programming language.
Array Names as Pointers
An array name is just a pointer, nothing more. To prove this, suppose you have the following array
declaration:
int ara[5] = {10, 20, 30, 40, 50};
If you printed ara[0], you would see 10. Because you now fully understand arrays, this is the value you
would expect.
But what if you were to print *ara? Would *ara print anything? If so, what? If you thought an error
message would print because ara is not a pointer but an array, you would be wrong. An array name is a
pointer. If you print *ara, you also would see 10.
Recall how arrays are stored in memory. Figure below, shows how ara would be mapped in memory.
The array name, ara, is nothing more than a pointer pointing to the first element of the array. Therefore,
if you dereference that pointer, you dereference the value stored in the first element of the array, which
is 10. Dereferencing ara is exactly the same thing as referencing to ara[0], because they both produce
the same value.

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

My sister’s maiden name was Bettye Lou Horn


My sister’s married name is Henderson
Why didn’t the full string print? Because the address pointed to by c was incremented by 11, c still
points to Henderson, so that was all that printed.
4. You might guess at a way to fix the previous program. Rather than printing the string stored at c after
assigning it to Henderson, you might want to decrement it by 11 so it points to its original location, the
start of the name. The code to do this follows, but it does not work as expected. Study the program
before reading the explanation.
// 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.
c -= 11; // Makes c point to its
// original location (???).
cout << “My sister’s married name is “ << c << “\n”;
return;
}
This program produces garbage at the second cout. There are actually two string literals in this program.
When you first assign c to Bettye Lou Horn, C++ reserves space in memory for the constant string and
puts the starting address of the string in c.
When the program then assigns c to Henderson, C++ finds room for another character constant, as
shown in Figure 27.3. If you subtract 11 from the location of c, after it points to the new string
Henderson, c points to an area of memory your program is not using. There is no guarantee that
printable data appears before the string constant Henderson. If you want to manipulate parts of the
string, you must do so an element at a time, just as you must with arrays.
Pointer Arithmetic

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

int *ip = iara; // The pointer points to


// The start of the array.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n”;
ip++; // Two are actually added.
cout << *ip << “\n\n”;
cout << “The integer size is “ << sizeof(int);
cout << “ bytes on this machine \n\n”;
return;
}
2. Here is the same program using a character array and a character pointer. Because a character takes
only one byte of storage, incrementing a character pointer actually adds just one to the pointer; only
one is needed because the characters are only one byte apart.
// Increments a pointer through a character array.
#include <iostream.h>
void main()
{
char cara[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’};
char *cp = cara; // The pointers point to
// the start of the array.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n”;
cp++; // One is actually added.
cout << *cp << “\n”;

Page 9
CSC2302 Department of Mathematics and Computer Science

cp++; // One is actually added.


cout << *cp << “\n\n”;
cout << “The character size is “ << sizeof(char);
cout << “ byte on this machine\n”;
return;
}
3. The next program shows the many ways you can add to, subtract from, and reference arrays and
pointers. The program defines a floating-point array and a floating-point pointer. The body of the
program prints the values from the array using array and pointer notation.
// Comprehensive reference of arrays and pointers.
#include <iostream.h>
void main()
{
float ara[] = {100.0, 200.0, 300.0, 400.0, 500.0};
float *fptr; // Floating-point pointer.
// Make pointer point to array’s first value.
fptr = &ara[0]; // Also could have been this:
// fptr = ara;
cout << *fptr << “\n”; // Prints 100.0
fptr++; // Points to next floating-point value.
cout << *fptr << “\n”; // Prints 200.0
fptr++; // Points to next floating-point value.
cout << *fptr << “\n”; // Prints 300.0
fptr++; // Points to next floating-point value.
cout << *fptr << “\n”; // Prints 400.0
fptr++; // Points to next floating-point value.
cout << *fptr << “\n”; // Prints 500.0
fptr = ara; // Points to first element again.
cout << *(fptr+2) << “\n”; // Prints 300.00 but
// does not change fptr.
// References both array and pointer using subscripts.
cout << (fptr+0)[0] << “ “ << (ara+0)[0] << “\n”;

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

You might also like