Array & Pointers
5.1One Dimensional Array
5.2 Two Dimensional Arrays
5.3 Relationship between Array & Pointers
5.4 Functions & Array-Passing by Reference
5.5 Simple Pointer Mathematics
5.6 Character Pointers
One Dimensional Array
Also known as single-dimensional array
Is defined as
◦ a list of related values, that have the same
data type being stored in a single group
◦ the group name is referred to as array name
General syntax of an array declaration
statement:
dataType arrayName[number-of-items]
Example 5.1 #include <iostream>
using namespace std;
int main()
{
const int MAXTEMPS = 5;
int i, temp[MAXTEMPS];
for (i = 0; i < MAXTEMPS; i++) // Enter the temperatures
{
cout << "Enter a temperature: ";
cin >> temp[i];
}
cout << endl;
for (i = 0; i < MAXTEMPS; i++) // Print the temperatures
cout << "temperature " << i << " is " << temp[i] << endl;
return 0;
}
Output Enter a temperature: 85
Enter a temperature: 90
Enter a temperature: 78
Enter a temperature: 75
Enter a temperature: 92
temperature 0 is 85
temperature 1 is 90
temperature 2 is 78
temperature 3 is 75
temperature 4 is 92
Array Initialization
Initializing elements in an array must be included in braces
Example code #include <iostream>
using namespace std;
int main()
{
const int MAXELS = 5;
int i, max, nums[MAXELS] = {2, 18, 1, 27, 16};
max = nums[0];
for (i = 1; i < MAXELS; i++)
if (max < nums[i])
max = nums[i];
cout << "The maximum value is " << max << endl;
return 0;
}
Two Dimensional Arrays Also known as table
Consist of
◦ both rows and columns of elements
Below is an example of two dimensional array
8 16 9 52
3 15 27 6
14 25 2 10
This array consists of 3 row and 4 column and declared as int val [3] [4];
Example 5.2 #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int NUMROWS = 3;
const int NUMCOLS = 4;
int i, j;
int val[NUMROWS][NUMCOLS] = {8,16,9,52,3,15,27,6,14,25,2,10};
cout << "\nDisplay of val array by explicit element"
<< endl << setw(4) << val[0][0] << setw(4) << val[0][1]
<< setw(4) << val[0][2] << setw(4) << val[0][3]
<< endl << setw(4) << val[1][0] << setw(4) << val[1][1]
<< setw(4) << val[1][2] << setw(4) << val[1][3]
<< endl << setw(4) << val[2][0] << setw(4) << val[2][1]
<< setw(4) << val[2][2] << setw(4) << val[2][3];
cout << "\n\nDisplay of val array using a nested for loop";
for (i = 0; i < NUMROWS; i++)
{
cout << endl; // print a new line for each row
for (j = 0; j < NUMCOLS; j++)
cout << setw(4) << val[i][j];
}
cout << endl;
return 0;
}
Modify this example so that it will multiply each
element in the val array by the scalar number 10 and
display the resulting value.
Output Display of val array by explicit element
8 16 9 52
3 15 27 6
14 25 2 10
Display of val array using a nested for loop
8 16 9 52
3 15 27 6
14 25 2 10
Relationship between Array &
Pointers
Recall on Pointers
◦ operator, & means “the address of.”
Displaying Address
◦ &num means the address of num,
◦ &miles means the
◦ address of miles, and
◦ &foo means the address of foo
Storing Address
◦ numAddr = #
◦ numAddr is known as pointer variables or pointers
Using Address
◦ * symbol, when followed by a pointer means “the
variable whose address is stored in.”
◦ *numAddr means the variable whose address is
stored in numAddr.
Declaring Pointers
◦ pointers must be declared before they can be
used to store an address
◦ Example int *numAddr;
Reference and Pointer
◦ a reference is a named constant for an address
◦ the address named as a reference can’t be
altered compared to address in a pointer which
can be changed
◦ Also known as alias and is declared as
dataType& newName = existingName
◦ Recall Alias & Pointers
Alias Pointer
int b; // b is an integer variable
int& a = b; // a is a reference variable
that stores b's address
a = 10; // this changes b's value to 10
int b; // b is an integer variable
int *a = &b; // a is a pointer - store
b's address in a
*a = 10; // this changes b's value to
10 by explicit dereference of the
address in a
So, what is the relationship between array and
pointers?
&grade[3] = &grade[0] + (3 * sizeof(int))
How does the compiler locate grade[3] ?
Example 5.3
#include <iostream>
using namespace std;
int main()
{
const int ARRAYSIZE = 5;
int i, grade[ARRAYSIZE] = {98, 87, 92, 79, 85};
for (i = 0; i < ARRAYSIZE; i++)
cout << "\nElement " << i << " is " << grade[i];
cout << endl;
return 0;
} Where to put these two statements in the above code
to portray the relationship between array and pointer?
1)int *gPtr;
2)*(gPtr + i);
Use gPtr as variable to store grade[0] and to obtain value stored in
grade[0], use pointer *gPtr
The rest of the array is accessed by offset of the starting pointer
Two ways of 1)by subscripts and 2)by pointers and offsets
The relationship between array elements and pointers
Functions & Array-Passing by
Reference
When an array is passed to a function, its
address is the only item actually passed
“Address”means the address of the first
location used to store the array, as shown
below
Example 5.4 #include <iostream>
using namespace std;
int findMax(int [], int); // function prototype
int main()
{
const int NUMPTS = 5;
int nums[NUMPTS] = {2, 18, 1, 27, 16};
cout << "\nThe maximum value is "
<< findMax(nums,NUMPTS) << endl;
return 0;
}
// this function returns the maximum value in an array of ints
int findMax(int vals[], int numels)
{
int i, max = vals[0];
for (i = 1; i < numels; i++)
if (max < vals[i])
max = vals[i];
return max;
}
1st version of modified findMax()
◦ The parameter named vals in the function header
declaration for findMax() actually receives the
address of the nums array.
◦ Therefore, vals is really a pointer because pointers
are variables (or parameters) used to store
addresses.
int findMax(int *vals, int numels) // find the maximum value
{
int i, max = *vals;
for (i = 1; i < numels; i++)
if (max < *(vals + i) )
max = *(vals + i);
return max;
}
2nd version of modified findMax()
◦ use pointer arithmetic to change the address in
the pointer.
◦ After each array element is retrieved by using the
address in vals, the address is incremented by
one in the altering list of the for statement.
int findMax(int *vals, int numels) // find the maximum value
{
int i, max = *vals++; // get the first element and increment it
for (i = 1; i < numels; i++, vals++)
{
if (max < *vals)
max = *vals;
}
return max;
}
Passing an array equivalent to passing an address, thus,
any valid address can be passed.
For example, the function call findMax(&nums[2],3)
passes the address of nums[2] to findMax()
In findMax(), the pointer vals stores the address,
and the function starts the search for a
maximum at the element corresponding to this
address.
Therefore, from findMax()’s perspective, it has
received an address and proceeds appropriately.
Simple Pointer Mathematics
Adding and subtracting numbers to pointers is performed to obtain different addresses
Before performing arithmetic on pointers, meaningful addresses must be first introduced.
For example, set the address of nums[0] in nPt ◦ nPt = &nums[0]; or
◦ nPt = nums;
After nPt contains a valid address, values can be added and subtracted from the address to produce new addresses
Based on the above figure, what is the new address if
nPt = nPt + 4 is performed?
(Consider that each storage is 4 bytes)
Addresses can also be incremented or decremented
with the prefix and postfix increment and decrement
operators
If the pointer variable p is a pointer to an integer, the
expression p++ increments the address in the pointer
to point to the next integer
The increment and decrement operators can be
applied as both prefix and postfix pointer operator.
All the following combinations using pointers are valid:
*ptNum++ // use the pointer and then increment it
*++ptNum // increment the pointer before using it
*ptNum-- // use the pointer and then decrement it
*--ptNum // decrement the pointer before using it
Example 5.5 #include <iostream>
using namespace std;
int main()
{
const int NUMS = 5;
int nums[NUMS] = {16, 54, 7, 43, -5};
int i, total = 0, *nPt;
nPt = nums; // store address of nums[0] in nPt
for (i = 0; i < NUMS; i++)
total = total + *nPt++;
cout << "The total of the array elements is " << total << endl;
return 0;
}
Pointers can also be compared, which is particularly
useful when dealing with pointers that point to
elements in the same array.
For example, instead of using a counter in a for loop to
access each array element, the address in a pointer can
be compared to the array’s starting and ending
addresses.
nPt <= &nums[4]
Example 5.6 #include <iostream>
using namespace std;
int main()
{
const int NUMS = 5;
int nums[NUMS] = {16, 54, 7, 43, -5};
int total = 0, *nPt;
nPt = nums; // store address of nums[0] in nPt
while (nPt < nums + NUMS)
total += *nPt++;
cout << "The total of the array elements is " << total << endl;
return 0;
}
Pointer Initialization ◦ When initializing pointers, however, you must be careful
to set an address in the pointer.
◦ For example, an initialization such as int *ptNum = &miles;
is valid only if miles is declared as an integer variable before ptNum.
◦ If the variable miles is declared after ptNum is declared, as follows, an error occurs: int *ptNum = &miles;
int miles;
◦ The error occurs because the address of miles is used before miles has even been defined.
◦ This is because the storage area reserved for miles hasn’t been allocated when ptNum is declared,
Character Pointer
String literals are arrays that contain all its characters plus the terminating null-character, with each of the elements being of type const char
For example
const char * foo = "hello";
This declares an array with the literal representation for "hello", and then a pointer to its first element is assigned to foo.
If we imagine that "hello" is stored at the
memory locations that start at address 1702,
we can represent the previous declaration as:
The pointer foo points to a sequence of
characters.