PFE Lecture Week4

48
PFE / SEM2 2013/2014 Faculty of Manufacturing Universiti Malaysia Pahang Kampus Pekan, Pahang Darul Makmur Tel: +609-424 5800 Fax: +609-4245888 BFM/BHM 2013 PROGRAMMING FOR ENGINEERS Week 4 Pointers and Array Relationship between pointers and array Pointer arithmetic Initialize pointer Compare pointers Pointers as function arguments Pointers to constant & constant pointer

Transcript of PFE Lecture Week4

Page 1: PFE Lecture Week4

PFE / SEM2 2013/2014

Faculty of ManufacturingUniversiti Malaysia Pahang

Kampus Pekan, Pahang Darul MakmurTel: +609-424 5800Fax: +609-4245888

BFM/BHM 2013 PROGRAMMING FOR ENGINEERS

Week 4

Pointers and Array• Relationship between

pointers and array• Pointer arithmetic• Initialize pointer

• Compare pointers• Pointers as function

arguments• Pointers to constant &

constant pointer

Page 2: PFE Lecture Week4

PFE / SEM2 2013/2014 2

9.3 Relationship Between Arrays and Pointers

• Array name can be used as a pointer constantint vals[] = {4, 7, 11};cout << *vals; // displays 4

• Pointer can be used as an array nameint *valptr = vals;cout << valptr[1]; // displays 7

Page 3: PFE Lecture Week4

PFE / SEM2 2013/2014 3

Program 9-5// This program shows an array name being dereferenced // with the * operator.

#include <iostream.h>

void main(void){

short numbers[] = {10, 20, 30, 40, 50};

cout << "The first element of the array is ";cout << *numbers << endl;

}

Page 4: PFE Lecture Week4

PFE / SEM2 2013/2014 4

Program Output

The first element in the array is 10

Page 5: PFE Lecture Week4

PFE / SEM2 2013/2014

Pointers in Expressions

• Given:int vals[]={4,7,11};int *valptr = vals;

• What is valptr + 1? • It means (address in valptr) + (1 * size of an int)

cout << *(valptr+1); // displays 7cout << *(valptr+2); // displays 11

• Must use ( ) in expression

10-5

Page 6: PFE Lecture Week4

PFE / SEM2 2013/2014

Array Access

Array elements can be accessed in many ways

10-6

Array access method

Example

array name and [ ] vals[2] = 17;

pointer to array and [ ] valptr[2] = 17;

array name and subscript arithmetic

*(vals+2) = 17;

pointer to array and subscript arithmetic

*(valptr+2) = 17;

Page 7: PFE Lecture Week4

PFE / SEM2 2013/2014

Array Access

• Array notation

vals[i]

is equivalent to the pointer notation

*(vals + i)• No bounds checking performed on array

access

10-7

Page 8: PFE Lecture Week4

PFE / SEM2 2013/2014 8

Figure 9-3

numbers

numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

Page 9: PFE Lecture Week4

PFE / SEM2 2013/2014 9

Figure 9-4

numbers

numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]

(numbers+1) (numbers+2) (numbers+3) (numbers+4)

Page 10: PFE Lecture Week4

PFE / SEM2 2013/2014 10

Program 9-6

// This program processes the contents of an array. Pointer// notation is used.#include <iostream.h>

void main(void){

int numbers[5];

cout << "Enter five numbers: ";for (int count = 0; count < 5; count++)

cin >> *(numbers + count);cout << "Here are the numbers you entered:\n";for (int count = 0; count < 5; count++)

cout << *(numbers + count)<< " ";cout << endl;

}

Page 11: PFE Lecture Week4

PFE / SEM2 2013/2014 11

Program Output with Example Input

Enter five numbers: 5 10 15 20 25 [Enter]Here are the numbers you entered:5 10 15 20 25

Page 12: PFE Lecture Week4

PFE / SEM2 2013/2014 12

Program 9-7// This program uses subscript notation with a pointer and// pointer notation with an array name.

#include <iostream.h>

void main(void){

float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};float *floatPtr; // Pointer to a floatint count; // array index

floatPtr = coins; // floatPtr now points to coins arraycout.precision(2);cout << "Here are the values in the coins array:\n";

Page 13: PFE Lecture Week4

PFE / SEM2 2013/2014 13

Program continues

for (count = 0; count < 5; count++)cout << floatPtr[count] << " ";

cout << "\nAnd here they are again:\n";for (count = 0; count < 5; count++)

cout << *(coins + count) << " ";cout << endl;

}

Page 14: PFE Lecture Week4

PFE / SEM2 2013/2014 14

Program Output

Here are the values in the coins array:0.05 0.1 0.25 0.5 1And here they are again:0.05 0.1 0.25 0.5 1

Page 15: PFE Lecture Week4

PFE / SEM2 2013/2014 15

Program 9-8// This program uses the address of each element in

the array.

#include <iostream.h>#include <iomanip.h>

void main(void){

float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};float *floatPtr; // Pointer to a floatint count; // array indexcout.precision(2);cout << "Here are the values in the coins array:\n";

Page 16: PFE Lecture Week4

PFE / SEM2 2013/2014 16

Program continues

for (count = 0; count < 5; count++){

floatPtr = &coins[count];cout << *floatPtr << " ";

}cout << endl;

}

Page 17: PFE Lecture Week4

PFE / SEM2 2013/2014 17

Program Output

Here are the values in the coins array:0.05 0.1 0.25 0.5 1

Page 18: PFE Lecture Week4

PFE / SEM2 2013/2014 18

9.4 Pointer Arithmetic

• Some mathematical operations may be performed on pointers.– The ++ and – operators may be used to increment

or decrement a pointer variable.– An integer may be added to or subtracted from a

pointer variable. This may be performed with the +, - +=, or -= operators.

– A pointer may be subtracted from another pointer.

Page 19: PFE Lecture Week4

PFE / SEM2 2013/2014

Pointer Arithmetic

Assume the variable definitions int vals[]={4,7,11}; int *valptr = vals; Examples of use of ++ and -- valptr++; // points at 7 valptr--; // now points at 4

10-19

Page 20: PFE Lecture Week4

PFE / SEM2 2013/2014

10-20

More on Pointer Arithmetic

Assume the variable definitions:

int vals[]={4,7,11};

int *valptr = vals;

Example of the use of + to add an int to a pointer:

cout << *(valptr + 2)

This statement will print 11

Page 21: PFE Lecture Week4

PFE / SEM2 2013/2014

10-21

Assume the variable definitions:

int vals[]={4,7,11};

int *valptr = vals;

Example of use of +=:

valptr = vals; // points at 4

valptr += 2; // points at 11

More on Pointer Arithmetic

Page 22: PFE Lecture Week4

PFE / SEM2 2013/2014

10-22

More on Pointer Arithmetic

Assume the variable definitions

int vals[] = {4,7,11};

int *valptr = vals;

Example of pointer subtraction

valptr += 2;

cout << valptr - val;

This statement prints 2: the number of

ints between valptr and val

Page 23: PFE Lecture Week4

PFE / SEM2 2013/2014 23

Program 9-9

// This program uses a pointer to display the contents// of an integer array.#include <iostream.h>

void main(void){

int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};int *nums, index;nums = set;cout << "The numbers in set are:\n";for (index = 0; index < 8; index++){

cout << *nums << " ";nums++;

}

Page 24: PFE Lecture Week4

PFE / SEM2 2013/2014 24

Program continues

cout << "\nThe numbers in set backwards are:\n";for (index = 0; index < 8; index++){

nums--;cout << *nums << " ";

}}

Page 25: PFE Lecture Week4

PFE / SEM2 2013/2014 25

Program Output

The numbers in set are:5 10 15 20 25 30 35 40The numbers in set backwards are:40 35 30 25 20 15 10 5

Page 26: PFE Lecture Week4

PFE / SEM2 2013/2014

10.5 Initializing Pointers

• Can initialize to NULL or 0 (zero) int *ptr = NULL;• Can initialize to addresses of other variables

int num, *numPtr = &num;int val[ISIZE], *valptr = val;

• Initial value must have correct typefloat cost;int *ptr = &cost; // won't work

10-26

Page 27: PFE Lecture Week4

PFE / SEM2 2013/2014 27

9.6 Comparing Pointers

• If one address comes before another address in memory, the first address is considered “less than” the second. C++’s relational operators maybe used to compare pointer values.

Page 28: PFE Lecture Week4

PFE / SEM2 2013/2014

10.6 Comparing Pointers• Relational operators can be used to compare

addresses in pointers• Comparing addresses in pointers is not the

same as comparing contents pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares

// contents

10-28

Page 29: PFE Lecture Week4

PFE / SEM2 2013/2014 29

Figure 9-5

0x5A00

array[0] array[1] array[2] array[3] array[4]

0x5A04 0x5A08 0x5A0C 0x5A0F

(Addresses)

An array of five integers

Page 30: PFE Lecture Week4

PFE / SEM2 2013/2014 30

Program 9-10// This program uses a pointer to display the contents// of an integer array.#include <iostream.h>

void main(void){

int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};int *nums = set; // Make nums point to set

cout << "The numbers in set are:\n";cout << *nums << " "; // Display first elementwhile (nums < &set[7]){

nums++;cout << *nums << " ";

}

Page 31: PFE Lecture Week4

PFE / SEM2 2013/2014 31

Program continues

cout << "\nThe numbers in set backwards are:\n";cout << *nums << " "; // Display last elementwhile (nums > set){

nums--;cout << *nums << " ";

}}

Page 32: PFE Lecture Week4

PFE / SEM2 2013/2014 32

Program Output

The numbers in set are:5 10 15 20 25 30 35 40The numbers in set backwards are:40 35 30 25 20 15 10 5

Page 33: PFE Lecture Week4

PFE / SEM2 2013/2014 33

9.7 Pointers as Function Parameters

• A pointer can be used as a function parameter. It gives the function access to the original argument, much like a reference parameter does.

Page 34: PFE Lecture Week4

PFE / SEM2 2013/2014

10.7 Pointers as Function Parameters

• A pointer can be a parameter• Works like a reference parameter to allow

change to argument from within function• A pointer parameter must be explicitly

dereferenced to access the contents at that address

10-34

Page 35: PFE Lecture Week4

PFE / SEM2 2013/2014

Pointers as Function Parameters

Requires: 1) asterisk * on parameter in prototype and heading

void getNum(int *ptr); 2) asterisk * in body to dereference the pointer

cin >> *ptr; 3) address as argument to the function

getNum(&num);

10-35

Page 36: PFE Lecture Week4

PFE / SEM2 2013/2014

Pointers as Function Parameters

void swap(int *x, int *y) { int temp;

temp = *x; *x = *y; *y = temp;

} int num1 = 2, num2 = -3; swap(&num1, &num2);

10-36

Page 37: PFE Lecture Week4

PFE / SEM2 2013/2014 37

Program 9-11

// This program uses two functions that accept addresses of// variables as arguments.#include <iostream.h>

// Function prototypesvoid getNumber(int *);void doubleValue(int *);

void main(void){

int number;getNumber(&number) // Pass address of number to getNumberdoubleValue(&number); // and doubleValue.cout << "That value doubled is " << number << endl;

}

Page 38: PFE Lecture Week4

PFE / SEM2 2013/2014 38

Program continues// Definition of getNumber. The parameter, Input, is a pointer.// This function asks the user for a number. The value entered// is stored in the variable pointed to by Input.

void getNumber(int *input){

cout << "Enter an integer number: ";cin >> *input;

}

// Definition of doubleValue. The parameter, val, is a pointer.// This function multiplies the variable pointed to by val by// two.

void doubleValue(int *val){

*val *= 2;}

Page 39: PFE Lecture Week4

PFE / SEM2 2013/2014 39

Program Output with Example Input

Enter an integer number: 10 [Enter]That value doubled is 20

Page 40: PFE Lecture Week4

PFE / SEM2 2013/2014 40

Program 9-12// This program demonstrates that a pointer may be used as a // parameter to accept the address of an array. Either subscript// or pointer notation may be used.#include <iostream.h>#include <iomanip.h>

// Function prototypesvoid getSales(float *);float totalSales(float *);

void main(void){

float sales[4];

getSales(sales);cout.precision(2);

Page 41: PFE Lecture Week4

PFE / SEM2 2013/2014 41

Program continues

cout.setf(ios::fixed | ios::showpoint);cout << "The total sales for the year are $";cout << totalSales(sales) << endl;

}

// Definition of getSales. This function uses a pointer to accept// the address of an array of four floats. The function asks the // user to enter the sales figures for four quarters, and stores// those figures in the array. (The function uses subscript// notation.)

void getSales(float *array){

for (int count = 0; count < 4; count++){

cout << "Enter the sales figure for quarter ";cout << (count + 1) << ": ";cin >> array[count];

}}

Page 42: PFE Lecture Week4

PFE / SEM2 2013/2014 42

Program continues// Definition of totalSales. This function uses a pointer to// accept the address of an array of four floats. The function // gets the total of the elements in the array and returns that// value. (Pointer notation is used in this function.)

float totalSales(float *array){

float sum = 0.0;

for (int count = 0; count < 4; count++){

sum += *array;array++;

}return sum;

}

Page 43: PFE Lecture Week4

PFE / SEM2 2013/2014 43

Program Output with Example Input

Enter the sales figure for quarter 1: 10263.98 [Enter]Enter the sales figure for quarter 2: 12369.69 [Enter]Enter the sales figure for quarter 3: 11542.13 [Enter]Enter the sales figure for quarter 4: 14792.06 [Enter]The total sales for the year are $48967.86

Page 44: PFE Lecture Week4

PFE / SEM2 2013/2014

10.8 Ponters to Constants and Constant Pointers

• Pointer to a constant: cannot change the value that is pointed at

• Constant pointer: address in pointer cannot change once pointer is initialized

10-44

Page 45: PFE Lecture Week4

PFE / SEM2 2013/2014

Ponters to Constant

• Must use const keyword in pointer definition:const double taxRates[] =

{0.65, 0.8, 0.75};

const double *ratePtr;• Use const keyword for pointers in

function headers to protect data from modification from within function

10-45

Page 46: PFE Lecture Week4

PFE / SEM2 2013/2014

Pointer to Constant – What does the Definition Mean?

10-46

Page 47: PFE Lecture Week4

PFE / SEM2 2013/2014

Constant Pointers

• Defined with const keyword adjacent to variable name:int classSize = 24;int * const classPtr = &classSize;

• Must be initialized when defined• Can be used without initialization as a function

parameter– Initialized by argument when function is called– Function can receive different arguments on different calls

• While the address in the pointer cannot change, the data at that address may be changed

10-47

Page 48: PFE Lecture Week4

PFE / SEM2 2013/2014

Constant Pointer – What does the Definition Mean?

10-48