C++ Chapter

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

5.

Arrays, Pointers, and


References
This chapt er introduces the array, point er, and refer ence
dat a types and illustr at es their use for defining vari abl es.
An array consist s of a set of object s (called its
el e me nt s ), all of which are of the same type and are
arranged contiguousl y in memor y. In gener al , only the array
itself has a symbolic name, not its element s . Each element is
identified by an index which denot es the position of the
element in the array. The number of element s in an array is
called its di me ns i on . The dimensi on of an array is fixed and
predet er mi ne d; it cannot be changed during progra m
executi on.
Arrays are suit abl e for repr es ent i ng composi t e dat a which
consist of many similar, individual items. Exampl es include: a
list of names, a tabl e of world cities and their current
temper at ur es , or the mont hl y trans act i ons for a bank
account .
A poi nt er is simply the addr es s of an object in memor y.
Gener ally, object s can be access ed in two ways: directly by
their symbolic name, or indirectly through a point er. The act
of get ti ng to an object via a point er to it, is called
deref er e nci ng the point er. Point er vari abl es are defined to
point to object s of a specific type so that when the point er is
der ef er enced, a typed object is obt ai ned.
Point ers are useful for creati ng dynami c object s during
progr a m executi on. Unlike normal (global and local) object s
which are allocat ed storage on the runti me st ack, a dynami c
object is allocat ed memor y from a different storage area
called the heap . Dynami c object s do not obey the normal
scope rules. Their scope is explicitly cont rolled by the
progr a mme r .
A ref er e nc e provides an alt er nat i ve symbolic name
(ali as ) for an object. Accessi ng an object through a refer ence
is exactly the same as acces si ng it through its original name.
Refer ences offer the power of point er s and the conveni ence
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 65
of direct acces s to object s. They are used to support the call-
by- refer ence style of function parame t er s , especi ally when
large object s are being pass ed to functions.
66 C++ Programmi ng Copyright 1998 Pragmati x Soft ware
Arrays
An array vari abl e is defined by specifying its dimensi on and
the type of its element s. For exampl e, an array repr es e nt i ng
10 height meas ur e me nt s (each being an integer quant i t y)
may be defined as:
int heights[10];
The individual element s of the array are access ed by
indexi ng the array. The first array element always has the
index 0. Therefor e, heights[0] and heights[9] denot e,
respect i vel y, the first and last element of heights. Each of
heights element s can be treat ed as an integer vari abl e. So,
for exampl e, to set the third element to 177, we may writ e:
heights[2] = 177;
Attempt i ng to access a nonexi st ent array element (e. g.,
heights[-1] or heights[10]) leads to a serious runti me error
(called index out of bounds error).
Processi ng of an array usually involves a loop which goes
through the array element by element . Listing 5. 1 illustr at es
this using a function which takes an array of int eger s and
ret ur ns the aver age of its element s.
Listing 5.2
1

2
3
4
5
6
7
8
const int size = 3;
double Average (int nums[size])
{
double average = 0;
for (register i = 0; i < size; ++i)
average += nums[i];
return average/size;
}
Like other vari abl es, an array may have an initializer.
Braces are used to specify a list of comma- separ at ed initial
values for array element s. For exampl e,
int nums[3] = {5, 10, 15};
initializes the three element s of nums to 5, 10, and 15,
respect i vel y. When the number of values in the initializer is
less than the number of element s, the remai ni ng element s
are initialized to zero:
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 67
int nums[3] = {5, 10}; // nums[2] initializes to 0
When a compl et e initializer is used, the array dimensi on
becomes redundant , becaus e the number of element s is
implicit in the initializer. The first definition of nums can
ther efor e be equival ent l y writt en as:
int nums[] = {5, 10, 15}; // no dimension needed
Anot her situati on in which the dimensi on can be omitt ed
is for an array function par amet er . For exampl e, the Average
function above can be improved by rewriting it so that the
dimensi on of nums is not fixed to a const ant , but specified by
an additional parame t er . Listing 5. 3 illustr at es this.
Listing 5.4
1
2
3
4
5
6
7
double Average (int nums[], int size)
{
double average = 0;
for (register i = 0; i < size; ++i)
average += nums[i];
return average/size;
}
A C++ string is simply an array of char act er s. For
exampl e,
char str[] = "HELLO";
defines str to be an array of six char act er s: five lett ers and a
null char act er . The ter mi nat i ng null char act er is insert ed by
the compil er. By cont r ast ,
char str[] = {'H', 'E', 'L', 'L', 'O'};
defines str to be an array of five charact er s.
It is easy to calcul at e the dimensi on of an array using the
sizeof oper at or. For exampl e, given an array ar whose
element type is Type, the dimensi on of ar is:
sizeof(ar) / sizeof(Type)

68 C++ Programmi ng Copyright 1998 Pragmati x Soft ware


Multidi mensional Arrays
An array may have more than one dimensi on (i.e., two,
three, or higher). The organizati on of the array in memor y is
still the same (a contiguous sequence of element s), but the
progr a mme r s perceived organizat i on of the element s is
different . For exampl e, suppos e we wish to repr es ent the
aver age seasonal temper at ur e for three major Australi an
capit al cities (see Table 5. 1).
Table 5.2 Average seasonal temperature.
Spring Summer Autumn Winter
Sydney 26 34 22 17
Melbourne 24 32 19 13
Brisbane 28 38 25 20
This may be repres e nt e d by a two- dimensi onal array of
int eger s:
int seasonTemp[3][4];
The organizat i on of this array in memor y is as 12 consecut i ve
int eger element s. The progr a mme r , however, can imagi ne it
as three rows of four int eger ent ri es each (see Figure 5. 1).
igure 5.2 !rgani"ation of seasonTemp in memory.
...
32 19 13 28 38 25
...
26 34 22 17 24 20
irst ro" Se#ond ro" $%ird ro"
As befor e, element s are access ed by indexi ng the array.
A separ at e index is needed for each dimensi on. For exampl e,
Sydneys aver age summer temper at ur e (first row, second
column) is given by seasonTemp[0][1].
The array may be initialized using a nest ed initializer:
int seasonTemp[3][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
Becaus e this is mapped to a one- dimensi onal array of 12
element s in memor y, it is equival ent to:
int seasonTemp[3][4] = {
26, 34, 22, 17, 24, 32, 19, 13, 28, 38, 25, 20
};
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 69
The nest ed initializer is preferr ed becaus e as well as being
more informat i ve, it is more versatil e. For exampl e, it makes
it possi bl e to initialize only the first element of each row and
have the rest defaul t to zero:
int seasonTemp[3][4] = {{26}, {24}, {28}};
We can also omit the first dimensi on (but not subs eque nt
dimensi ons) and let it be derived from the initializer:
int seasonTemp[][4] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
Processi ng a multidi mensi onal array is similar to a one-
dimensi onal array, but uses nest ed loops inst ead of a single
loop. Listing 5. 5 illustrat es this by showing a function for
finding the highes t temper at ur e in seasonTemp.
Listing 5.#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const int rows = 3;
const int columns = 4;
int seasonTemp[rows][columns] = {
{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
int HighestTemp (int temp[rows][columns])
{
int highest = 0;
for (register i = 0; i < rows; ++i)
for (register j = 0; j < columns; ++j)
if (temp[i][j] > highest)
highest = temp[i][j];
return highest;
}

70 C++ Programmi ng Copyright 1998 Pragmati x Soft ware


Pointers
A point er is simply the address of a memor y location and
provides an indirect way of accessi ng dat a in memor y. A
point er vari abl e is defined to point to dat a of a specific
type. For exampl e:
int *ptr1; // pointer to an int
char *ptr2; // pointer to a char
The value of a point er vari abl e is the addr es s to which it
point s. For exampl e, given the definitions
int num;
we can writ e:
ptr1 = &num;
The symbol & is the addre s s oper at or; it takes a variabl e as
argument and ret ur ns the memor y addr es s of that vari abl e.
The effect of the above assignme nt is that the addr es s of num
is assi gned to ptr1. Therefor e, we say that ptr1 point s to num.
Figure 5. 3 illustr at es this diagr amma t i cally.
igure 5.4 A simple integer pointer.
ptr1 num
Given that ptr1 point s to num, the expr es si on
*ptr1
der ef er ences ptr1 to get to what it point s to, and is ther efor e
equival ent to num. The symbol * is the deref er e nc e oper at or;
it takes a point er as argument and ret ur ns the cont ent s of
the location to which it point s.
In gener al , the type of a point er must mat ch the type of
the dat a it is set to point to. A point er of type void*, however,
will mat ch any type. This is useful for defining point er s which
may point to dat a of different types, or whose type is
originally unknown.
A point er may be cas t (type conver t ed) to anot her type.
For exampl e,
ptr2 = (char*) ptr1;
conver t s ptr1 to char point er befor e assi gni ng it to ptr2.
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 71
Regar dl es s of its type, a point er may be assi gned the
value 0 (called the null point er). The null point er is used for
initializing point er s, and for marki ng the end of point er- based
dat a struct ur es (e. g., linked lists).

72 C++ Programmi ng Copyright 1998 Pragmati x Soft ware


$ynamic Memory
In addi tion to the progr am st ack (which is used for storing
global vari abl es and st ack frames for function calls), anot her
memory area, called the heap , is provided. The heap is used
for dynami cally allocati ng memor y blocks during progr am
executi on. As a result, it is also called dynami c memor y .
Similarly, the progr a m st ack is also called st ati c memor y .
Two oper at or s are used for allocati ng and deallocati ng
memory blocks on the heap. The new oper at or takes a type as
argument and allocat ed a memor y block for an object of that
type. It ret urns a point er to the allocat ed block. For exampl e,
int *ptr = new int;
char *str = new char[10];
allocat e, respect i vel y, a block for storing a single integer and
a block large enough for storing an array of 10 char act er s.
Memory allocat ed from the heap does not obey the same
scope rules as normal vari abl es. For exampl e, in
void Foo (void)
{
char *str = new char[10];
//...
}
when Foo ret ur ns, the local variabl e str is dest royed, but the
memory block point ed to by str is not . The latt er remai ns
allocat ed until explicitly releas ed by the progr a mme r .
The delete oper at or is used for releasi ng memor y blocks
allocat ed by new. It takes a point er as argume nt and releas es
the memor y block to which it point s. For exampl e:
delete ptr; // delete an object
delete [] str; // delete an array of objects
Not e that when the block to be del et ed is an array, an
addi tional [] shoul d be included to indicat e this. The
significance of this will be expl ained lat er when we discuss
classes.
Shoul d delete be appli ed to a point er which point s to
anyt hi ng but a dynami cally- allocat ed object (e.g., a variabl e
on the st ack), a serious runti me error may occur. It is
har ml ess to apply delete to the 0 point er.
Dynami c object s are useful for creati ng dat a which last
beyond the function call which creat es them. Listing 5. 7
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 73
illustrat es this using a function which takes a string
par amet er and ret urns a copy of the string.
Listing 5.%
1

2
3
4
5
6
7
#include <string.h>
char* CopyOf (const char *str)
{
char *copy = new char[strlen(str) + 1];
strcpy(copy, str);
return copy;
}
Annotation
1 This is the st andar d string header file which decl ar es a
vari et y of functions for mani pul ati ng strings.
4 The strlen function (decl ar ed in string.h) count s the
char act er s in its string argument up to (but excludi ng)
the final null char act er . Becaus e the null char act er is not
included in the count , we add 1 to the tot al and allocat e
an array of char act er s of that size.
5 The strcpy function (decl ar ed in string.h) copi es its
second argume nt to its first, char act er by char act er ,
including the final null char act er.
Becaus e of the limit ed memory resources, ther e is always
the possibility that dynami c memor y may be exhaus t e d
during progr a m executi on, especi ally when many large
blocks are allocat ed and none releas ed. Shoul d new be unabl e
to allocat e a block of the reques t e d size, it will ret ur n 0
inst ead. It is the responsi bility of the progr a mme r to deal
with such possi bilities. The except i on handling mechani s m of
C++ (expl ai ned in Chapt er 10) provides a practical met hod
of dealing with such probl ems.

74 C++ Programmi ng Copyright 1998 Pragmati x Soft ware


Pointer Arit&meti c
In C++ one can add an int eger quanti t y to or subt r act an
int eger quanti t y from a point er. This is frequent l y used by
progr a mme r s and is called point er arit hmet i c. Point er
arithmet i c is not the same as integer arithmet i c, becaus e the
outcome depends on the size of the object point ed to. For
exampl e, suppos e that an int is repr es ent e d by 4 byt es.
Now, given
char *str = "HELLO";
int nums[] = {10, 20, 30, 40};
int *ptr = &nums[0]; // pointer to first element
str++ advances str by one char (i.e., one byt e) so that it
point s to the second char act er of "HELLO", wher eas ptr++
advances ptr by one int (i.e., four byt es) so that it point s to
the second element of nums. Figure 5. 5 illustrat es this
diagr amma t i cally.
igure 5.# Pointer arit&metic.
& ' ( ( ) *0 10 20 30 40
str
str++
ptr
ptr++
It follows, ther efor e, that the element s of "HELLO" can be
referr ed to as *str, *(str + 1), *(str + 2), etc. Similarly, the
element s of nums can be referr ed to as *ptr, *(ptr + 1), *(ptr
+ 2), and *(ptr + 3).
Anot her form of point er arit hmet i c allowed in C++
involves subt r act i ng two point er s of the same type. For
exampl e:
int *ptr1 = &nums[1];
int *ptr2 = &nums[3];
int n = ptr2 - ptr1; // n becomes 2
Point er arithmet i c is very handy when processi ng the
element s of an array. Listing 5. 9 shows as an exampl e a
string copying function similar to strcpy.
Listing 5.'(
1
2
3
4
void CopyString (char *dest, char *src)
{
while (*dest++ = *src++)
;
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 75
5 }
76 C++ Programmi ng Copyright 1998 Pragmati x Soft ware
Annotation
3 The condi tion of this loop assi gns the cont ent s of src to
the cont ent s of dest and then increment s bot h point er s.
This condition becomes 0 when the final null char act er of
src is copi ed to dest.
In turns out that an array vari abl e (such as nums) is itself
the addr es s of the first element of the array it repr es e nt s.
Hence the element s of nums can also be referr ed to using
point er arit hmet i c on nums, that is, nums[i] is equival ent to
*(nums + i). The difference bet ween nums and ptr is that nums
is a const ant , so it cannot be made to point to anyt hi ng else,
wher eas ptr is a vari abl e and can be made to point to any
other integer.
Listing 5. 11 shows how the HighestTemp function (shown
earlier in Listing 5. 12 ) can be improved using point er
arithmet i c.
Listing 5.')
1
2
3

4
5
6
7
8
9
int HighestTemp (const int *temp, const int rows, const int columns)
{
int highest = 0;
for (register i = 0; i < rows; ++i)
for (register j = 0; j < columns; ++j)
if (*(temp + i * columns + j) > highest)
highest = *(temp + i * columns + j);
return highest;
}
Annotation
1 Inst ead of passi ng an array to the function, we pass an
int point er and two additional paramet er s which specify
the dimensi ons of the array. In this way, the function is
not rest rict ed to a specific array size.
6 The expr es si on *(temp + i * columns + j) is equival ent to
temp[i][j] in the previous version of this function.
HighestTemp can be simplified even furt her by treati ng temp
as a one- dimensi onal array of row * column integer s. This is
shown in Listing 5. 14 .
Listing 5.'5
1
2
3

4
5
int HighestTemp (const int *temp, const int rows, const int columns)
{
int highest = 0;
for (register i = 0; i < rows * columns; ++i)
if (*(temp + i) > highest)
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 77
6
7
8
highest = *(temp + i);
return highest;
}

78 C++ Programmi ng Copyright 1998 Pragmati x Soft ware


unction Pointers
It is possi bl e to take the addr es s of a function and store it in
a function point er. The point er can then be used to indirectly
call the function. For exampl e,
int (*Compare)(const char*, const char*);
defines a function pointer named Compare which can hold the address of any
function that takes two constant character pointers as arguments and returns
an integer. The string comparison library function strcmp, for example, is
such. Therefore:
Compare = &strcmp; // Compare points to strcmp function
The & operator is not necessary and can be omitted:
Compare = strcmp; // Compare points to strcmp function
Alternatively, the pointer can be defined and initialized at once:
int (*Compare)(const char*, const char*) = strcmp;
When a function address is assigned to a function pointer, the two types
must match. The above definition is valid because strcmp has a matching
function prototype:
int strcmp(const char*, const char*);
iven the above definition of Compare, strcmp can be either called
directly, or indirectly via Compare. The following three calls are e!uivalent:
strcmp("Tom", "Tim"); // direct call
(*Compare)("Tom", "Tim"); // indirect call
Compare("Tom", "Tim"); // indirect call (abbreviated)
A common use of a function pointer is to pass it as an argument to
another function" typically because the latter re!uires different versions of the
former in different circumstances. A good example is a binary search function
for searching through a sorted array of strings. This function may use a
comparison function #such as strcmp$ for comparing the search string against
the array strings. This might not be appropriate for all cases. %or example,
strcmp is case&sensitive. 'f we wanted to do the search in a non&case&sensitive
manner then a different comparison function would be needed.
As shown in (isting 5. 16 , by making the comparison function a
parameter of the search function, we can make the latter independent of the
former.
Listing 5.'*
1 int BinSearch (char *item, char *table[], int n,
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 79
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int (*Compare)(const char*, const char*))
{
int bot = 0;
int top = n - 1;
int mid, cmp;
while (bot <= top) {
mid = (bot + top) / 2;
if ((cmp = Compare(item,table[mid])) == 0)
return mid; // return item index
else if (cmp < 0)
top = mid - 1; // restrict search to lower half
else
bot = mid + 1; // restrict search to upper half
}
return -1; // not found
}
Annotation
1 Binary search is a well- known algorit hm for searchi ng
through a sort ed list of items. The search list is denot ed
by table which is an array of strings of dimensi on n. The
search item is denot ed by item.
2 Compare is the function point er to be used for compari ng
item agai nst the array element s.
7 Each time round this loop, the search span is reduced by
half. This is repeat ed until the two ends of the search
span (denot ed by bot and top) collide, or until a mat ch is
found.
9 The item is compar ed agai nst the middl e item of the
array.
10 If item mat ches the middl e item, the latt ers index is
ret ur ned.
11 If item is less than the middl e item, then the search is
rest rict ed to the lower half of the array.
14 If item is great er than the middl e item, then the search is
rest rict ed to the upper half of the array.
16 Ret urns -1 to indicat e that ther e was no mat chi ng item.
The following example shows how BinSearch may be called with strcmp
passed as the comparison function:
char *cities[] = {"Boston", "London", "Sydney", "Tokyo"};
cout << BinSearch("Sydney", cities, 4, strcmp) << '\n';
This will out put 2 as expect ed.
80 C++ Programmi ng Copyright 1998 Pragmati x Soft ware
References
A refer ence introduces an ali as for an object. The not at i on
for defining refer ences is similar to that of point er s, except
that & is used inst ead of *. For exampl e,
double num1 = 3.14;
double &num2 = num1; // num is a reference to num1
defines num2 as a refer ence to num1. After this definition num1
and num2 bot h refer to the same object , as if they were the
same vari abl e. It should be emphasi zed that a refer ence
does not creat e a copy of an object , but mer el y a symbolic
alias for it. Hence, aft er
num1 = 0.16;
bot h num1 and num2 will denot e the value 0.16.
A refer ence must always be initialized when it is defined:
it shoul d be an alias for somet hi ng. It would be illegal to
define a refer ence and initialize it lat er.
double &num3; // illegal: reference without an initializer
num3 = num1;
You can also initialize a refer ence to a const ant . In this
case a copy of the const ant is made (aft er any neces s ar y
type conver si on) and the refer ence is set to refer to the
copy.
int &n = 1; // n refers to a copy of 1
The reason that n becomes a refer ence to a copy of 1 rat her
than 1 itself is safet y. Consider what could happen if this
were not the case.
int &x = 1;
++x;
int y = x + 1;
The 1 in the first and the 1 in the third line are likely to be
the same object (most compil ers do const ant opti mizati on
and allocat e bot h 1s in the same memor y location). So
alt hough we expect y to be 3, it could turn out to be 4.
However, by forcing x to be a copy of 1, the compil er
guar ant e e s that the object denot ed by x will be different
from bot h 1s.
The most common use of refer ences is for function
par amet er s. Reference paramet er s facilit at es the pas s - by-
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 81
ref er e nc e style of argume nt s , as oppos ed to the pas s - by-
val ue style which we have used so far. To observe the
differences , consi der the three swap functions in Listing 5. 18 .
Listing 5.'+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Swap1 (int x, int y) // pass-by-value (objects)
{
int temp = x;
x = y;
y = temp;
}
void Swap2 (int *x, int *y) // pass-by-value (pointers)
{
int temp = *x;
*x = *y;
*y = temp;
}
void Swap3 (int &x, int &y) // pass-by-reference
{
int temp = x;
x = y;
y = temp;
}
Annotation
1 Although Swap1 swaps x and y, this has no effect on the
argument s pass ed to the function, becaus e Swap1 receives
a copy of the argument s . What happens to the copy does
not affect the original.
7 Swap2 overcomes the probl em of Swap1 by using point er
par amet er s inst ead. By der ef er enci ng the point er s, Swap2
get s to the original values and swaps them.
13 Swap3 overcome s the probl em of Swap1 by using refer ence
par amet er s inst ead. The parame t er s become aliases for
the argume nt s pass ed to the function and ther efor e swap
them as int ended.
Swap3 has the added advant age that its call synt ax is the
same as Swap1 and involves no addr es si ng or der ef er enci ng.
The following main function illustr at es the differences:
int main (void)
{
int i = 10, j = 20;
Swap1(i, j); cout << i << ", " << j << '\n';
Swap2(&i, &j); cout << i << ", " << j << '\n';
Swap3(i, j); cout << i << ", " << j << '\n';
}
82 C++ Programmi ng Copyright 1998 Pragmati x Soft ware
When run, it will produce the following out put :
10, 20
20, 10
10, 20
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 83
Typedefs
Typedef is a synt act ic facility for introduci ng symbolic names
for dat a types. Just as a refer ence defines an alias for an
object , a typedef defines an alias for a type. Its mai n use is to
simplify otherwi se complicat ed type decl ar at i ons as an aid to
improved readability. Here are a few exampl es:
typedef char *String;
Typedef char Name[12];
typedef unsigned int uint;
The effect of thes e definitions is that String becomes an alias
for char*, Name becomes an alias for an array of 12 chars, and
uint become s an alias for unsigned int. Therefor e:
String str; // is the same as: char *str;
Name name; // is the same as: char name[12];
uint n; // is the same as: unsigned int n;
The complicat ed decl ar ati on of Compare in (isting 5. 20 is a
good candi dat e for typedef:
typedef int (*Compare)(const char*, const char*);
int BinSearch (char *item, char *table[], int n, Compare comp)
{
//...
if ((cmp = comp(item, table[mid])) == 0)
return mid;
//...
}
The typedef introduces Compare as a new type name for any
function with the given prot ot ype. This makes BinSearchs
signat ur e arguabl y simpl er.

84 C++ Programmi ng Copyright 1998 Pragmati x Soft ware


,-ercises
5. 1 Define two functions which, respect i vel y, input values for the
element s of an array of real s and out put the array element s:
void ReadArray (double nums[], const int size);
void WriteArray (double nums[], const int size);
5. 2 Define a function which revers es the order of the element s of
an array of reals:
void Reverse (double nums[], const int size);
5. 3 The following tabl e specifies the maj or cont ent s of four
brands of breakf ast cereal s. Define a two- dimensi onal array
to capt ur e this dat a:
iber Sugar at Salt
$op la,e 12g 25g 16g 0-4g
.ornabi/ 22g 4g 8g 0-3g
)atabi/ 28g 5g 9g 0-5g
0ltrabran 32g 7g 2g 0-2g
Write a function which out put s this tabl e element by
element .
5. 4 Define a function to input a list of names and store them as
dynami cally- allocat ed strings in an array, and a function to
out put them:
void ReadNames (char *names[], const int size);
void WriteNames (char *names[], const int size);
Write anot her function which sort s the list using bubbl e sort:
void BubbleSort (char *names[], const int size);
Bubbl e sort involves repeat ed scans of the list, wher e during
each scan adj acent items are compar ed and swapped if out
of order. A scan which involves no swappi ng indicat es that
the list is sort ed.
5. 5 Rewrit e the following function using point er arit hmet i c:
char* ReverseString (char *str)
{
int len = strlen(str);
char *result = new char[len + 1];
for (register i = 0; i < len; ++i)
www. pragsof t . com Chapt er 5: Arrays, Point ers, and Ref erences 85
result[i] = str[len - i - 1];
result[len] = '\0';
return result;
}
5. 6 Rewrit e Bubbl eSort (from 5. 7) so that it uses a function
point er for compari son of names.
5. 8 Rewrit e the following using typedef s:
void (*Swap)(double, double);
char *table[];
char *&name;
usigned long *values[10][20];

86 C++ Programmi ng Copyright 1998 Pragmati x Soft ware

You might also like