Sunteți pe pagina 1din 6

AJ/Handout 14 -1- Object-Oriented Programming

Lesson 14
Objectives
 Pointers and Functions
 Pointers and C-Type Strings
Pointers and Functions
We already have studied that there are three ways to pass arguments to functions: by value, by
reference, and by pointers. If the function is intended to modify variables in the calling program,
their variable can not passed by values, since the function obtain only a copy of the variable.
However, either a reference argument or pointer can be used in this situation.
Passing Simple Variables
Here we will compare the reference argument with pointer.
// passref.cpp
// arguments passed by reference
#include <iostream>
using namespace std;
int main()
{
void centimize(double&); //prototype

double var = 10.0; //var has value of 10 inches


cout << "var = " << var << " inches" << endl;

centimize(var); //change var to centimeters


cout << "var = " << var << " centimeters" << endl;
return 0;
}
//--------------------------------------------------------------
void centimize(double& v)
{
v *= 2.54; //v is the same as var
}
Here in this example we simply showed how a pass by reference is used. The point to be noted is
that argument variable v is same is variable var in main(). Or these are two names for same
variable. Now we solve same problem with pointers.
// passptr.cpp
// arguments passed by pointer
#include <iostream>
using namespace std;
int main()
AJ/Handout 14 -2- Object-Oriented Programming

{
void centimize(double*); //prototype

double var = 10.0; //var has value of 10 inches


cout << "var = " << var << " inches" << endl;

centimize(&var); //change var to centimeters


cout << "var = " << var << " centimeters" << endl;
return 0;
}
//--------------------------------------------------------------
void centimize(double* ptrd)
{
*ptrd *= 2.54; //*ptrd is the same as var
}
In this program the function centimize took a pointer to double as argument and we call it by
sending the address-of variable var. Then it changes the value of var by multiplying it with 2.54
which is restored in original variable. Passing a pointer is in some ways similar to passing a
reference. Since both permit the variable in the calling program to be modified by the function. A
reference is an alias for the original variable, while a pointer is the address of the variable.
Passing Arrays
More elegant use of pointers is to pass arrays to the function. Since it saves memory of the system
and also faster than passing an array instead of its address only. Here we see in this program how
arrays are passed using pointers.
// passarr.cpp
// array passed by pointer
#include <iostream>
using namespace std;
const int MAX = 5; //number of array elements
int main()
{
void centimize(double*); //prototype

double varray[MAX] = { 10.0, 43.1, 95.9, 59.7, 87.3 };

centimize(varray); //change elements of varray to cm

for(int j=0; j<MAX; j++) //display new array values


cout << "varray[" << j << "]="
<< varray[j] << " centimeters" << endl;
AJ/Handout 14 -3- Object-Oriented Programming

return 0;
}
//--------------------------------------------------------------
void centimize(double* ptrd)
{
for(int j=0; j<MAX; j++)
*ptrd++ *= 2.54; //ptrd points to elements of varray
}
The prototype of the function is same as in previous program. Here only fact is utilized that array
name is its address and the meaning of double* is same as double[], but this syntax is not very
common.
Here a question arises: how the compiler will interpret *ptrd++ and *(ptrd++) and how does it
know whether to increment the contents of array or the pointer? This is not due to precedence but
it is because of associativity. Associativity is concerned with whether the compiler performs
operations starting with an operator on the right or an operator on the left. So in expression
*(ptrd++) first compiler will increment the pointer using ++ then the content of incremented
pointer will be displayed. While in this program contents are being altered by multiplication.
See book for sake of demonstrating the further examples of array access.
Pointers and C-Type String
As we have studied earlier, strings are nothing but array of characters. Thus pointer notation can be
applied to the characters in strings, just like arrays.
Pointers to String Constants
Here are some program listings which show how to define the string constant using array and
using pointers.
// twostr.cpp
// strings defined using array and pointer notation
#include <iostream>
using namespace std;
int main()
{
char str1[] = "Defined as an array";
char* str2 = "Defined as a pointer";
cout << str1 << endl; // display both strings
cout << str2 << endl;
// str1++; // can't do this; str1 is a constant
str2++; // this is OK, str2 is a pointer
cout << str2 << endl; // now str2 starts "efined..."
return 0;
}
AJ/Handout 14 -4- Object-Oriented Programming

In many ways these two types are equivalent. Like we can print both by same way, use them as
function arguments, and so on. But there is a subtle difference: str1 is an address—that is a pointer
constant—while str2 is a pointer variable. So str2 can be changed, while str1 cannot. So by
incrementing str2 means that it no longer points to the first character in the string. Also the string
defined using pointer is more flexible as shown in the example.
String as Function Arguments
The following program show a string used as a function argument. The function simply prints the
string, by accessing each character in turn.
// ptrstr.cpp
// displays a string with pointer notation
#include <iostream>
using namespace std;
int main()
{
void dispstr(char*); //prototype
char str[] = "Idle people have the least leisure.";
dispstr(str); //display the string
return 0;
}
//--------------------------------------------------------------
void dispstr(char* ps)
{
while( *ps ) //until null character,
cout << *ps++; //print characters
cout << endl;
}
Here in this example the function dispstr is called by str (a constant value) so a copy of this
constant is created in the function. And this copy is pointer ps, and a pointer can be changed so
function increments it. The expression *ps++ returns the successive characters of the string. The
loop cycles until it found null character. Whose value is 0 which works as false for the loop and it
terminates.
Copying a String Using Pointers
Now in this example we will see how the pointers are used to insert the values in the array.
// copystr.cpp
// copies one string to another with pointers
#include <iostream>
using namespace std;
int main()
{
AJ/Handout 14 -5- Object-Oriented Programming

void copystr(char*, const char*); //prototype


char* str1 = "Self-conquest is the greatest victory.";
char str2[80]; //empty string

copystr(str2, str1); //copy str1 to str2


cout << str2 << endl; //display str2
return 0;
}
//--------------------------------------------------------------
void copystr(char* dest, const char* src)
{
while( *src ) //until null character,
*dest++ = *src++; //copy chars from src to dest
*dest = '\0'; //terminate dest
}
In this program one by one characters are copied to destination string using *dest++=*src++. The
library function strcpy can also work with pointers. Its syntax could be written as:
char* strcpy(char* dest, const char* src);
It works very similar to our homemade function.
The const Modifier and Pointers
In previous program we have encountered a statement where const modifier is used with pointer.
Following statements show the possibilities:
const int* cptrInt; //cptrInt is a pointer to constant integer
int* const ptrconst; //ptrconst is a constant pointer to integer
In first case we can not change the value to integer since that is a constant but we can change the
value to pointer; while in second case we can change the value of integer but can’t change the
pointer. We can make the difference by reading the line right to left. Also we can put const on both
places to make the scene further unchangeable.
Array of Pointers to Strings
Just as there are arrays of variables to type integer or float, there can also arrays of pointers. A
common use for this construction is array of pointers to strings. In this program a two dimensional
array is accommodated in one without any struggle.
// ptrtostr.cpp
// an array of pointers to strings
#include <iostream>
using namespace std;
const int DAYS = 7; //number of pointers in array
int main()
AJ/Handout 14 -6- Object-Oriented Programming

{ //array of pointers to char


char* arrptrs[DAYS] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday",
"Friday", "Saturday" };
for(int j=0; j<DAYS; j++) //display every string
cout << arrptrs[j] << endl;
return 0;
}
When strings are not part of an array, C++ places them contiguously in memory, so there is no
wasted space. However, to find the strings, there must be an array that holds pointers to them. A
string is an array of char, so an array of pointers to strings is an array of pointers to char. See the
diagram on page 458.

S-ar putea să vă placă și