SlideShare a Scribd company logo
1 of 35
A First Book of C++A First Book of C++
Chapter 8 (Pt 2)Chapter 8 (Pt 2)
Arrays and PointersArrays and Pointers
∗ In this chapter, you will learn about:
∗ Introduction to Pointers
∗ Array Names as Pointers
∗ Pointer Arithmetic
∗ Passing Addresses
∗ Common Programming Errors
A First Book of C++ 4th Edition 2
Objectives
∗ If grade is a single-dimensional array containing five
integers, the fourth element is grade[3]
∗ C++ compiler computation of the address of grade[3]:
(assuming 4 bytes per integer)
&grade[3] = &grade[0] + (3 * 4)
col*byte size (offset)
∗ This statement reads as “the address of grade[3] equals
the address of grade[0] plus 12”
∗ Figure 8.12 illustrates the address computation used to locate
grade[3]
A First Book of C++ 4th Edition 3
Array Names as Pointers
A First Book of C++ 4th Edition 4
Array Names as Pointers (cont'd.)
∗ Offset: number of positions beyond first element in
array
∗ Using offset, we can simulate process used by
computer to access array elements
∗ Example (Figure 8.14 and Table 8.1):
∗ Store address of grade[0] in pointer gPtr
∗ Use offset to find location of grade[3]
∗ Expression *(gPtr + 3) references variable that is
three integers beyond variable pointed to by gPtr
A First Book of C++ 4th Edition 5
Array Names as Pointers (cont'd.)
A First Book of C++ 4th Edition 6
Array Names as Pointers (cont'd.)
A First Book of C++ 4th Edition 7
Array Names as Pointers (cont'd.)
//Program 8.6 – Method 1, assign starting address to pointer
#include <iostream>
using namespace std;
int main()
{
const int ARRAYSIZE = 5;
int *gptr; // declare a pointer to an int
int i, grade[ARRAYSIZE] = {98,87,92,79,85};
gptr = &grade[0]; // store starting of array address
for (i=0; i < ARRAYSIZE; i++)
cout << “nElement ” << i << “ is “ << *(gptr + i);
cout << endl;
return 0;
}
Accessing Array Elements using Pointers 1Accessing Array Elements using Pointers 1
A First Book of C++ 4th Edition 8
//Program 8.7 – Method 2, use array itself as pointer
#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;
}
Accessing Array Elements Using Pointers 2Accessing Array Elements Using Pointers 2
A First Book of C++ 4th Edition 9
∗ Static array allocation: as variables are defined,
storage is assigned from a memory pool
∗ Specific memory locations are fixed for life of a variable,
used or not
∗ Example: function requests storage for an array of
500 integers
∗ If application requires less than 500 integers, unused
storage is not released until array goes out of scope
∗ If more than 500 integers required, array size must be
increased and the function recompiled
A First Book of C++ 4th Edition 10
Dynamic Array Allocation
∗ Dynamic allocation: storage allocated is determined
and adjusted as program is run
∗ Useful when dealing with lists
∗ Allows list to expand and contract as list items are
added and deleted
∗ Example: constructing list of grades
∗ Don’t know number of grades ultimately needed
∗ Need a mechanism to enlarge and shrink array
∗ new and delete operators: provide capability
A First Book of C++ 4th Edition 11
Dynamic Array Allocation (cont’d.)
A First Book of C++ 4th Edition 12
Dynamic Array Allocation (cont'd.)
∗ Dynamic storage requests for scalar variables or
arrays made in declaration or assignment statements
∗ Example 1 (assign value to pointer upon declaration):
int *num = new int;
∗ Reserves space for an integer variable
∗ Stores address of this variable into pointer num
A First Book of C++ 4th Edition 13
Dynamic Array Allocation (cont'd.)
∗ Example 2: same function as Example 1
(declare pointer first, assign value in next statement)
int *num;
num = new int;
∗ Heap: free storage area of a computer
∗ Consists of unallocated memory, can be allocated to a
running program
∗ In Examples 1 and 2, new storage comes from free
storage area (heap)
A First Book of C++ 4th Edition 14
Dynamic Array Allocation (cont'd.)
∗ Example of dynamic allocation of an array:
int *grade = new int[200];
∗ Statement reserves storage for 200 integers and places address
of first integer into pointer grade
∗ Same example with variable dimension
cout << "Enter the number of grades to be"
<< " processed: ";
cin >> numgrades;
int *grades = new int[numgrades];
∗ Size of array depends on user input
∗ Values accessed by array notation: grades[i]
∗ Values accessed by pointer notation: *(grades+i)
A First Book of C++ 4th Edition 15
Dynamic Array Allocation (cont'd.)
∗ By adding to and subtracting from pointers, we can
obtain different addresses
∗ Pointers can be compared using relational operators (
==, !=, <, >, etc.)
∗ Consider declarations:
int nums[100];
int *nPt;
∗ Set address of nums[0] into nPt using:
nPt = &nums[0];
nPt = nums;
A First Book of C++ 4th Edition 16
Pointer Arithmetic
similar (an array is by default a pointer)
∗ After nPt is assigned a valid address, values can be
added or subtracted to produce new addresses
∗ Scaling: automatic adjustment of computed address,
ensures points to value of correct type
∗ Example: nPt = nPt + 4;
∗ Assuming an integer requires 4 bytes, the computer
multiplies 4 by 4 and adds 16 to the address in nPt
A First Book of C++ 4th Edition 17
Pointer Arithmetic (cont'd.)
computing new address
A First Book of C++ 4th Edition 18
Pointer Arithmetic (cont'd.)
+4 bytes +4 bytes +4 bytes +4 bytes
∗ Pointers can be initialized when declared
∗ Example: int *ptNum = &miles;
∗ Above initialization valid only if miles was declared as an integer
prior to above statement
∗ The following statements produce an error
int *ptNum = &miles;//miles not declared yet
int miles;
∗ Arrays can be initialized within declarations
double *zing = &prices[0];
∗ This statement is valid if prices has already been declared as
a double-precision array
A First Book of C++ 4th Edition 19
Pointer Initialization
∗ Passing addresses to function using reference
variables was addressed in Chapter 6
∗ Implied use of addresses because the reference does
provide the function with an address
∗ The function call swap(num1, num2) does not tell
whether parameters are passed by value or reference
∗ Must look at function prototype or header line to
determine
A First Book of C++ 4th Edition 20
Passing Addresses
∗ Explicit passing of an address to a function: place the
address operator (&) in front of variable being passed
∗ Example (Figure 8.19 and Program 8.11):
swap(&firstnum, &secnum);//in function call
∗ This function call passes the addresses of firstnum and
secnum to swap()
∗ Explicitly passing addresses using the address operator is
effectively a pass by reference
A First Book of C++ 4th Edition 21
Passing Addresses (cont'd.)
A First Book of C++ 4th Edition 22
Passing Addresses (cont'd.)
A First Book of C++ 4th Edition 23
Passing Addresses (cont'd.)
∗ When array is passed to a function, address of first
location is the only item passed
∗ Program 8.13 passes an array to a function using
conventional array notation
A First Book of C++ 4th Edition 24
Passing Arrays
A First Book of C++ 4th Edition 25
//vals = &nums[0]
∗ Parameter vals in header line declaration for
findMax() in Program 8.13 actually receives the
address of array nums
∗ Thus, val is really a pointer
∗ Another suitable header line for findMax() is:
int findMax(int *vals, int numels)
// here vals is declared as a pointer
// to an integer
A First Book of C++ 4th Edition 26
Passing Arrays (cont'd.)
∗ Access to multidimensional arrays can be made using
pointer notation
∗ Example: consider the declaration:
int nums[2][3] = { {16,18,20},
{25,26,27} };
∗ Creates an array of elements and a set of pointer
constants named nums, nums[0], and nums[1] (as
shown in Figure 8.26)
A First Book of C++ 4th Edition 27
Advanced Pointer Notation
Advanced Pointer Notation (cont'd.)Advanced Pointer Notation (cont'd.)
A First Book of C++ 4th Edition 28
∗ Two-dimensional array pointer constants allow for
accessing array elements in several ways
∗ Address of first element in first row of nums is
nums[0]
∗ Address of first element in second row is nums[1]
∗ Variable pointed to by nums[0] is num[0][0]
∗ Variable pointed to by nums[1] is num[1][0]
∗ Each element can be accessed by applying an offset
to the correct pointer
A First Book of C++ 4th Edition 29
Advanced Pointer Notation (cont'd.)
A First Book of C++ 4th Edition 30
Advanced Pointer Notation (cont'd.)
Pointer Notation Subscript Notation Values
*(*nums) nums[0][0] 16
*(*nums + 1) nums[0][1] 18
*(*nums + 2) nums[0][2] 20
*(*(nums + 1)) nums[1][0] 25
*(*(nums + 1) + 1) nums[1][1] 26
*(*(nums + 1) + 2) nums[1][2] 27
∗ Attempting to explicitly store an address in a variable that
has not been declared as a pointer
∗ Using a pointer to access nonexistent array elements
∗ Incorrectly applying address and indirection operators
∗ If pt is a pointer variable, the expressions:
pt = &45 //must be variable name, e.g:&num
pt = &(miles + 10)//&(miles + num)-> ok
are both invalid because they attempt to take
the address of a value
A First Book of C++ 4th Edition 31
Common Programming Errors
∗ Taking addresses of pointer constants
∗ For example, given the declarations:
int nums[25];
int *pt;
the assignment pt = &nums; //INVALID
∗ nums is a pointer constant that is itself equivalent to an
address; the correct assignment is :
pt = nums OR pt = &nums[0]
∗ Taking addresses of a reference argument, reference
variable, or register variable
A First Book of C++ 4th Edition 32
Common Programming Errors
(cont'd.)
∗ Initializing pointer variables incorrectly
∗ Initialization int *pt = 5; // INVALID
∗ pt is a pointer to an integer; it must be initialized with a valid
address
∗ Becoming confused about whether a variable contains an
address or is an address
int &dist = miles; // contains an address or is an address???
int dist = &miles; // contains an address or is an address???
∗ Forgetting to use the bracket set, [ ], after the delete or
new operator when dynamically allocating or deallocating
memory
A First Book of C++ 4th Edition 33
Common Programming Errors
(cont'd.)
∗ Every variable has: data type, address, value
∗ A pointer is a variable that is used to store the address
of another variable
∗ An array name is a pointer constant
∗ Access to an array element using a subscript can
always be replaced using a pointer
∗ Arrays can be dynamically created as a program is
executing
A First Book of C++ 4th Edition 34
Summary
∗ Arrays are passed to functions as addresses
∗ When a single-dimensional array is passed to a
function, the parameter declaration for the function
can be either an array declaration or a pointer
declaration
∗ Pointers can be incremented, decremented,
compared, and assigned
A First Book of C++ 4th Edition 35
Summary (cont'd.)

More Related Content

What's hot

C programming session 05
C programming session 05C programming session 05
C programming session 05
Vivek Singh
 
10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer
웅식 전
 
Chapter Eight(1)
Chapter Eight(1)Chapter Eight(1)
Chapter Eight(1)
bolovv
 

What's hot (20)

Ch9c
Ch9cCh9c
Ch9c
 
Three Address code
Three Address code Three Address code
Three Address code
 
Pointers
PointersPointers
Pointers
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
 
Arrays
ArraysArrays
Arrays
 
Used of Pointer in C++ Programming
Used of Pointer in C++ ProgrammingUsed of Pointer in C++ Programming
Used of Pointer in C++ Programming
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
10. array & pointer
10. array & pointer10. array & pointer
10. array & pointer
 
Three address code generation
Three address code generationThree address code generation
Three address code generation
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Chapter Eight(1)
Chapter Eight(1)Chapter Eight(1)
Chapter Eight(1)
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2Learning C++ - Pointers in c++ 2
Learning C++ - Pointers in c++ 2
 
Arrays
ArraysArrays
Arrays
 
Pointers_c
Pointers_cPointers_c
Pointers_c
 
pointers
pointerspointers
pointers
 
Electrical Engineering Exam Help
Electrical Engineering Exam HelpElectrical Engineering Exam Help
Electrical Engineering Exam Help
 

Viewers also liked

SPIRIT AWARD Q4 spirit Magazine
SPIRIT AWARD Q4 spirit MagazineSPIRIT AWARD Q4 spirit Magazine
SPIRIT AWARD Q4 spirit Magazine
Tegan Marroquin
 
Introduction fundamentals sets and sequences (notes)
Introduction  fundamentals sets and sequences (notes)Introduction  fundamentals sets and sequences (notes)
Introduction fundamentals sets and sequences (notes)
IIUM
 
Csc1100 lecture01 ch01 pt2-paradigm (1)
Csc1100 lecture01 ch01 pt2-paradigm (1)Csc1100 lecture01 ch01 pt2-paradigm (1)
Csc1100 lecture01 ch01 pt2-paradigm (1)
IIUM
 
Museo De Genalguacil
Museo De GenalguacilMuseo De Genalguacil
Museo De Genalguacil
bertha reyes
 
Array
ArrayArray
Array
Hajar
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
Neveen Reda
 
7079581 quantitative-techniques-for-management
7079581 quantitative-techniques-for-management7079581 quantitative-techniques-for-management
7079581 quantitative-techniques-for-management
lakshmi narayana murthy
 

Viewers also liked (20)

Algo>Arrays
Algo>ArraysAlgo>Arrays
Algo>Arrays
 
International Market entry strategies: Agency Model
International Market entry strategies: Agency ModelInternational Market entry strategies: Agency Model
International Market entry strategies: Agency Model
 
SPIRIT AWARD Q4 spirit Magazine
SPIRIT AWARD Q4 spirit MagazineSPIRIT AWARD Q4 spirit Magazine
SPIRIT AWARD Q4 spirit Magazine
 
Group project overall
Group project overallGroup project overall
Group project overall
 
Introduction fundamentals sets and sequences (notes)
Introduction  fundamentals sets and sequences (notes)Introduction  fundamentals sets and sequences (notes)
Introduction fundamentals sets and sequences (notes)
 
Csc1100 lecture01 ch01 pt2-paradigm (1)
Csc1100 lecture01 ch01 pt2-paradigm (1)Csc1100 lecture01 ch01 pt2-paradigm (1)
Csc1100 lecture01 ch01 pt2-paradigm (1)
 
Museo De Genalguacil
Museo De GenalguacilMuseo De Genalguacil
Museo De Genalguacil
 
Uso de comandos insert, update y delete en bases de datos de sql server
Uso de comandos insert, update y delete en bases de datos de sql serverUso de comandos insert, update y delete en bases de datos de sql server
Uso de comandos insert, update y delete en bases de datos de sql server
 
C++ arrays part1
C++ arrays part1C++ arrays part1
C++ arrays part1
 
Substituindo o request message no mule
Substituindo o request message no muleSubstituindo o request message no mule
Substituindo o request message no mule
 
Array
ArrayArray
Array
 
C++ L04-Array+String
C++ L04-Array+StringC++ L04-Array+String
C++ L04-Array+String
 
Educational issues in the context of urbanization, globalization and privatiz...
Educational issues in the context of urbanization, globalization and privatiz...Educational issues in the context of urbanization, globalization and privatiz...
Educational issues in the context of urbanization, globalization and privatiz...
 
Hex bolt drawings
Hex bolt drawingsHex bolt drawings
Hex bolt drawings
 
Aprendizaje in 2
Aprendizaje in 2Aprendizaje in 2
Aprendizaje in 2
 
Aprendizaje invisible 2
Aprendizaje invisible 2Aprendizaje invisible 2
Aprendizaje invisible 2
 
9781285852744 ppt ch08
9781285852744 ppt ch089781285852744 ppt ch08
9781285852744 ppt ch08
 
Arrays Class presentation
Arrays Class presentationArrays Class presentation
Arrays Class presentation
 
7079581 quantitative-techniques-for-management
7079581 quantitative-techniques-for-management7079581 quantitative-techniques-for-management
7079581 quantitative-techniques-for-management
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 

Similar to Csc1100 lecture12 ch08_pt2

Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1
IIUM
 
Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2
IIUM
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
Csc1100 lecture14 ch16_pt2
Csc1100 lecture14 ch16_pt2Csc1100 lecture14 ch16_pt2
Csc1100 lecture14 ch16_pt2
IIUM
 
03-arrays-pointers.ppt
03-arrays-pointers.ppt03-arrays-pointers.ppt
03-arrays-pointers.ppt
ArifKamal36
 
03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt
suriyakalavinoth
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
Dushmanta Nath
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
SAFFI Ud Din Ahmad
 

Similar to Csc1100 lecture12 ch08_pt2 (20)

Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1Csc1100 lecture07 ch07_pt1-1
Csc1100 lecture07 ch07_pt1-1
 
Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2Csc1100 lecture09 ch07_pt2
Csc1100 lecture09 ch07_pt2
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Csc1100 lecture14 ch16_pt2
Csc1100 lecture14 ch16_pt2Csc1100 lecture14 ch16_pt2
Csc1100 lecture14 ch16_pt2
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
03-arrays-pointers.ppt
03-arrays-pointers.ppt03-arrays-pointers.ppt
03-arrays-pointers.ppt
 
03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt03-arrsfdrgdgdfh65575675ays-pointers.ppt
03-arrsfdrgdgdfh65575675ays-pointers.ppt
 
03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt03-arrays-pointers (1).ppt
03-arrays-pointers (1).ppt
 
arrays, pointers and operations pointers
arrays, pointers and operations pointersarrays, pointers and operations pointers
arrays, pointers and operations pointers
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
 
Arrays
ArraysArrays
Arrays
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 

More from IIUM (20)

How to use_000webhost
How to use_000webhostHow to use_000webhost
How to use_000webhost
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Kreydle internship-multimedia
Kreydle internship-multimediaKreydle internship-multimedia
Kreydle internship-multimedia
 
03phpbldgblock
03phpbldgblock03phpbldgblock
03phpbldgblock
 
Chap2 practice key
Chap2 practice keyChap2 practice key
Chap2 practice key
 
Group p1
Group p1Group p1
Group p1
 
Tutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seoTutorial import n auto pilot blogspot friendly seo
Tutorial import n auto pilot blogspot friendly seo
 
Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009Visual sceneperception encycloperception-sage-oliva2009
Visual sceneperception encycloperception-sage-oliva2009
 
03 the htm_lforms
03 the htm_lforms03 the htm_lforms
03 the htm_lforms
 
Exercise on algo analysis answer
Exercise on algo analysis   answerExercise on algo analysis   answer
Exercise on algo analysis answer
 
Redo midterm
Redo midtermRedo midterm
Redo midterm
 
Heaps
HeapsHeaps
Heaps
 
Report format
Report formatReport format
Report format
 
Edpuzzle guidelines
Edpuzzle guidelinesEdpuzzle guidelines
Edpuzzle guidelines
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Final Exam Paper
Final Exam PaperFinal Exam Paper
Final Exam Paper
 
Group assignment 1 s21516
Group assignment 1 s21516Group assignment 1 s21516
Group assignment 1 s21516
 
Avl tree-rotations
Avl tree-rotationsAvl tree-rotations
Avl tree-rotations
 
Week12 graph
Week12   graph Week12   graph
Week12 graph
 

Csc1100 lecture12 ch08_pt2

  • 1. A First Book of C++A First Book of C++ Chapter 8 (Pt 2)Chapter 8 (Pt 2) Arrays and PointersArrays and Pointers
  • 2. ∗ In this chapter, you will learn about: ∗ Introduction to Pointers ∗ Array Names as Pointers ∗ Pointer Arithmetic ∗ Passing Addresses ∗ Common Programming Errors A First Book of C++ 4th Edition 2 Objectives
  • 3. ∗ If grade is a single-dimensional array containing five integers, the fourth element is grade[3] ∗ C++ compiler computation of the address of grade[3]: (assuming 4 bytes per integer) &grade[3] = &grade[0] + (3 * 4) col*byte size (offset) ∗ This statement reads as “the address of grade[3] equals the address of grade[0] plus 12” ∗ Figure 8.12 illustrates the address computation used to locate grade[3] A First Book of C++ 4th Edition 3 Array Names as Pointers
  • 4. A First Book of C++ 4th Edition 4 Array Names as Pointers (cont'd.)
  • 5. ∗ Offset: number of positions beyond first element in array ∗ Using offset, we can simulate process used by computer to access array elements ∗ Example (Figure 8.14 and Table 8.1): ∗ Store address of grade[0] in pointer gPtr ∗ Use offset to find location of grade[3] ∗ Expression *(gPtr + 3) references variable that is three integers beyond variable pointed to by gPtr A First Book of C++ 4th Edition 5 Array Names as Pointers (cont'd.)
  • 6. A First Book of C++ 4th Edition 6 Array Names as Pointers (cont'd.)
  • 7. A First Book of C++ 4th Edition 7 Array Names as Pointers (cont'd.)
  • 8. //Program 8.6 – Method 1, assign starting address to pointer #include <iostream> using namespace std; int main() { const int ARRAYSIZE = 5; int *gptr; // declare a pointer to an int int i, grade[ARRAYSIZE] = {98,87,92,79,85}; gptr = &grade[0]; // store starting of array address for (i=0; i < ARRAYSIZE; i++) cout << “nElement ” << i << “ is “ << *(gptr + i); cout << endl; return 0; } Accessing Array Elements using Pointers 1Accessing Array Elements using Pointers 1 A First Book of C++ 4th Edition 8
  • 9. //Program 8.7 – Method 2, use array itself as pointer #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; } Accessing Array Elements Using Pointers 2Accessing Array Elements Using Pointers 2 A First Book of C++ 4th Edition 9
  • 10. ∗ Static array allocation: as variables are defined, storage is assigned from a memory pool ∗ Specific memory locations are fixed for life of a variable, used or not ∗ Example: function requests storage for an array of 500 integers ∗ If application requires less than 500 integers, unused storage is not released until array goes out of scope ∗ If more than 500 integers required, array size must be increased and the function recompiled A First Book of C++ 4th Edition 10 Dynamic Array Allocation
  • 11. ∗ Dynamic allocation: storage allocated is determined and adjusted as program is run ∗ Useful when dealing with lists ∗ Allows list to expand and contract as list items are added and deleted ∗ Example: constructing list of grades ∗ Don’t know number of grades ultimately needed ∗ Need a mechanism to enlarge and shrink array ∗ new and delete operators: provide capability A First Book of C++ 4th Edition 11 Dynamic Array Allocation (cont’d.)
  • 12. A First Book of C++ 4th Edition 12 Dynamic Array Allocation (cont'd.)
  • 13. ∗ Dynamic storage requests for scalar variables or arrays made in declaration or assignment statements ∗ Example 1 (assign value to pointer upon declaration): int *num = new int; ∗ Reserves space for an integer variable ∗ Stores address of this variable into pointer num A First Book of C++ 4th Edition 13 Dynamic Array Allocation (cont'd.)
  • 14. ∗ Example 2: same function as Example 1 (declare pointer first, assign value in next statement) int *num; num = new int; ∗ Heap: free storage area of a computer ∗ Consists of unallocated memory, can be allocated to a running program ∗ In Examples 1 and 2, new storage comes from free storage area (heap) A First Book of C++ 4th Edition 14 Dynamic Array Allocation (cont'd.)
  • 15. ∗ Example of dynamic allocation of an array: int *grade = new int[200]; ∗ Statement reserves storage for 200 integers and places address of first integer into pointer grade ∗ Same example with variable dimension cout << "Enter the number of grades to be" << " processed: "; cin >> numgrades; int *grades = new int[numgrades]; ∗ Size of array depends on user input ∗ Values accessed by array notation: grades[i] ∗ Values accessed by pointer notation: *(grades+i) A First Book of C++ 4th Edition 15 Dynamic Array Allocation (cont'd.)
  • 16. ∗ By adding to and subtracting from pointers, we can obtain different addresses ∗ Pointers can be compared using relational operators ( ==, !=, <, >, etc.) ∗ Consider declarations: int nums[100]; int *nPt; ∗ Set address of nums[0] into nPt using: nPt = &nums[0]; nPt = nums; A First Book of C++ 4th Edition 16 Pointer Arithmetic similar (an array is by default a pointer)
  • 17. ∗ After nPt is assigned a valid address, values can be added or subtracted to produce new addresses ∗ Scaling: automatic adjustment of computed address, ensures points to value of correct type ∗ Example: nPt = nPt + 4; ∗ Assuming an integer requires 4 bytes, the computer multiplies 4 by 4 and adds 16 to the address in nPt A First Book of C++ 4th Edition 17 Pointer Arithmetic (cont'd.) computing new address
  • 18. A First Book of C++ 4th Edition 18 Pointer Arithmetic (cont'd.) +4 bytes +4 bytes +4 bytes +4 bytes
  • 19. ∗ Pointers can be initialized when declared ∗ Example: int *ptNum = &miles; ∗ Above initialization valid only if miles was declared as an integer prior to above statement ∗ The following statements produce an error int *ptNum = &miles;//miles not declared yet int miles; ∗ Arrays can be initialized within declarations double *zing = &prices[0]; ∗ This statement is valid if prices has already been declared as a double-precision array A First Book of C++ 4th Edition 19 Pointer Initialization
  • 20. ∗ Passing addresses to function using reference variables was addressed in Chapter 6 ∗ Implied use of addresses because the reference does provide the function with an address ∗ The function call swap(num1, num2) does not tell whether parameters are passed by value or reference ∗ Must look at function prototype or header line to determine A First Book of C++ 4th Edition 20 Passing Addresses
  • 21. ∗ Explicit passing of an address to a function: place the address operator (&) in front of variable being passed ∗ Example (Figure 8.19 and Program 8.11): swap(&firstnum, &secnum);//in function call ∗ This function call passes the addresses of firstnum and secnum to swap() ∗ Explicitly passing addresses using the address operator is effectively a pass by reference A First Book of C++ 4th Edition 21 Passing Addresses (cont'd.)
  • 22. A First Book of C++ 4th Edition 22 Passing Addresses (cont'd.)
  • 23. A First Book of C++ 4th Edition 23 Passing Addresses (cont'd.)
  • 24. ∗ When array is passed to a function, address of first location is the only item passed ∗ Program 8.13 passes an array to a function using conventional array notation A First Book of C++ 4th Edition 24 Passing Arrays
  • 25. A First Book of C++ 4th Edition 25 //vals = &nums[0]
  • 26. ∗ Parameter vals in header line declaration for findMax() in Program 8.13 actually receives the address of array nums ∗ Thus, val is really a pointer ∗ Another suitable header line for findMax() is: int findMax(int *vals, int numels) // here vals is declared as a pointer // to an integer A First Book of C++ 4th Edition 26 Passing Arrays (cont'd.)
  • 27. ∗ Access to multidimensional arrays can be made using pointer notation ∗ Example: consider the declaration: int nums[2][3] = { {16,18,20}, {25,26,27} }; ∗ Creates an array of elements and a set of pointer constants named nums, nums[0], and nums[1] (as shown in Figure 8.26) A First Book of C++ 4th Edition 27 Advanced Pointer Notation
  • 28. Advanced Pointer Notation (cont'd.)Advanced Pointer Notation (cont'd.) A First Book of C++ 4th Edition 28
  • 29. ∗ Two-dimensional array pointer constants allow for accessing array elements in several ways ∗ Address of first element in first row of nums is nums[0] ∗ Address of first element in second row is nums[1] ∗ Variable pointed to by nums[0] is num[0][0] ∗ Variable pointed to by nums[1] is num[1][0] ∗ Each element can be accessed by applying an offset to the correct pointer A First Book of C++ 4th Edition 29 Advanced Pointer Notation (cont'd.)
  • 30. A First Book of C++ 4th Edition 30 Advanced Pointer Notation (cont'd.) Pointer Notation Subscript Notation Values *(*nums) nums[0][0] 16 *(*nums + 1) nums[0][1] 18 *(*nums + 2) nums[0][2] 20 *(*(nums + 1)) nums[1][0] 25 *(*(nums + 1) + 1) nums[1][1] 26 *(*(nums + 1) + 2) nums[1][2] 27
  • 31. ∗ Attempting to explicitly store an address in a variable that has not been declared as a pointer ∗ Using a pointer to access nonexistent array elements ∗ Incorrectly applying address and indirection operators ∗ If pt is a pointer variable, the expressions: pt = &45 //must be variable name, e.g:&num pt = &(miles + 10)//&(miles + num)-> ok are both invalid because they attempt to take the address of a value A First Book of C++ 4th Edition 31 Common Programming Errors
  • 32. ∗ Taking addresses of pointer constants ∗ For example, given the declarations: int nums[25]; int *pt; the assignment pt = &nums; //INVALID ∗ nums is a pointer constant that is itself equivalent to an address; the correct assignment is : pt = nums OR pt = &nums[0] ∗ Taking addresses of a reference argument, reference variable, or register variable A First Book of C++ 4th Edition 32 Common Programming Errors (cont'd.)
  • 33. ∗ Initializing pointer variables incorrectly ∗ Initialization int *pt = 5; // INVALID ∗ pt is a pointer to an integer; it must be initialized with a valid address ∗ Becoming confused about whether a variable contains an address or is an address int &dist = miles; // contains an address or is an address??? int dist = &miles; // contains an address or is an address??? ∗ Forgetting to use the bracket set, [ ], after the delete or new operator when dynamically allocating or deallocating memory A First Book of C++ 4th Edition 33 Common Programming Errors (cont'd.)
  • 34. ∗ Every variable has: data type, address, value ∗ A pointer is a variable that is used to store the address of another variable ∗ An array name is a pointer constant ∗ Access to an array element using a subscript can always be replaced using a pointer ∗ Arrays can be dynamically created as a program is executing A First Book of C++ 4th Edition 34 Summary
  • 35. ∗ Arrays are passed to functions as addresses ∗ When a single-dimensional array is passed to a function, the parameter declaration for the function can be either an array declaration or a pointer declaration ∗ Pointers can be incremented, decremented, compared, and assigned A First Book of C++ 4th Edition 35 Summary (cont'd.)