Chapter 5 (Part I) - Pointers
Chapter 5 (Part I) - Pointers
Computer Programming
Chapter 5
Pointers
Chere L. (M.Tech)
Lecturer, SWEG, AASTU
1
Outline
▪ Variables in a Memory ▪ Pointers Expression
▪ Basics of Pointers Pointers Arithmetic
▪ What is pointer? Pointers Comparison
▪ Why pointers ▪ Pointers and Constants
▪ Pointer Declaration ▪ Pointers and Arrays/Strings
▪ Pointers Initialization ▪ Pointers with Function
▪ Pointer Operators (& and *) Parameter pass-by-address
▪ Types of Pointers Pointer as return type/value
NULL Pointer ▪ Dynamic Memory Management
Void pointers Memory Allocation (new)
Pointers of Pointer Memory Allocation (delete)
Dangling Pointers ▪ Smart Pointers (new)
Wild Pointers
Chapter 5 2
1) Variables in a Memory
Variable is a named memory that characterized by its identifier (place
holder), Data type (type + size), Value its store, Scope, Memory Address.
Each variable occupies some bytes in memory (according to its size; one
byte char, 4 bytes int)
i.e. depend on the size of the data type of the Variables, it
allocated memory slot(S)
Basically memory consists of consecutive, numbered storage cells
(slots), see next slide
And the assigned memory slot(s) identified by its memory address which
is a hexadecimal notation. e.g. 0x01AC4D
The memory address allocation depends on computer/operating system
and vary (changed) from execution to execution.
Chapter 5 3
1) Variables in a Memory (Cont’d)
Memory Allocation
When we create a these
variables sum, age,
average it tells our
program to reserve
4bytes, 2bytes, 8bytes of
RAM in memory
respectively
• And then associate the
address of the first byte
(base address) of each
allocated memory
(90000000, 90000004,
90000006) to the
variables name and
restrict the type of data
to be stored to the
specified data types.
Chapter 5 4
1) Variables in a Memory (Cont’d)
Analogy for Memory Allocation • Each lot on the map has a sequential number
along some street with the streets themselves
numbered sequentially. Each lot is the same size,
say 20’ by 100’.
• Now suppose people buy some of the lots and
build houses.
• Suppose a developer takes the first 4 lots (1302-
1308 51st Street) and builds an apartment
building, calling it the "Park Arms".
• Also Mr. Jones and Ms. Smith each decide to
build big houses, a ranch and a colonial,
respectively, which span two lots each (1310-
1312 and 1318-1320), and that Mr. Green and
Mrs. Brown each decide to build a similar modest
one-lot houses (1314 and 1316).
• The lots still have their numbers, so that the post-
office can deliver mail, but people know the
buildings by the appropriate names, "The Park
Arms", the "Jones" ranch, the "Brown" house, the
"Green" house and the "Smith" colonial
Chapter 5 5
1) Variables in a Memory (Cont’d)
In general, Variable Identifier
Is just a “symbolic name” and a reference to that memory address.
The compiler is responsible to maintain the details of the variable in the
symbol table to manage the assigned memory location.
… … 100 … 1024 …
a
Variable num’s value, i.e., 100, is
int num = 100; stored at memory location 1024
Chapter 5 6
2) Basics of Pointers
Chapter 5 7
2) Basics of Pointers (cont’d)
Chapter 5 10
2) Basics of Pointers (cont’d)
2.4 Pointer Initialization
The memory associated with what pointer is pointing to is NOT
allocated/created just by the defining of pointer,
i.e., int *ptr; - doesn’t allocate any memory for ptr to point to
A pointer can be initialized to any valid variable address or to NULL.
Chapter 5 13
3. Pointer Operators
3.1 Address of Operator (&)
The "address of “ operator (&) is a unary operator that returns
(gives) the memory address of its operand (variable).
It can be used in front of any variable object and the result of the
operation is the location in memory of the variable
Syntax:
&variable_name // Here the operand is a valid identifier.
Example 1:
int a = 100;
// get the value
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024 Chapter 5 14
3. Pointer Operators (cont’d)
Example 2: Program to demonstrate of Address of Operator (&)
#include <iostream>
using namespace std;
void main(){
int num = 88, item = 100; Result is:
The address of a is: 1020
cout << "The address of a is: " << &num << endl; The address of b is: 1024
cout << "The address of b is: " << &item << endl;
Syntax:
*pointer_name // the operand should be not NULL pointer
Chapter 5 17
3. Pointer Operators (cont’d)
Example 1: Dereferencing
Memory address: 1020 1024 1032
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
int *ptr = 0;
//error, Cannot dereference a
cout<<*ptr<<endl; pointer whose value is null
Chapter 5 18
3. Pointer Operators (cont’d)
Don’t be confused between pointer definition and
dereferencing which use the same operator (*)….
Chapter 5 22
4. Types of Pointers (cont’d)
4.1 Void pointer
The void pointer, also known as the generic pointer, is a special type of
pointer that can be pointed at objects of any data type.
A void pointer is declared like a normal pointer, using the void keyword
as the pointer’s type.
Example
Chapter 5 23
4. Types of Pointers (cont’d)
Chapter 5 24
4. Types of Pointers (cont’d)
Example 1: predict output
What is the
output?
Chapter 5 25
4. Types of Pointers (cont’d)
* ptr = k+10;
cout << "x = " << k << endl;
What is the output?
**proptr = *ptr + k;
cout << “k = " << k << endl;
58 58 58
}
Chapter 5 26
4. Types of Pointers (cont’d)
Exercise 5.1 Output?
1. int i = 5, j = 10; Value
Line
2. int *ptr; i j ptr pptr
3. int **pptr;
4
4. ptr = &i;
5
5. pptr = &ptr;
6. *ptr = 3; 6
7. **pptr = 7; 7
8. ptr = &j; 8
9. **pptr = 9; 9
10. *pptr = &i;
10
11. *ptr = -2;
11
Chapter 5 27
5. Pointers Expression
7.1 Pointers Arithmetic
Only two arithmetic operations, addition and subtraction, may be
performed on pointers.
When we add 1 to a pointer, we are actually adding the size of data type
in bytes, the pointer is pointing at.
e.g. int *ptr; ptr++;
address = pointer + size of element
Assume if current address of x is 1000, then x++ statement will increase x
by 4 (size of int data type) and makes it 1004, not 1001.
58 58 58
Chapter 5 29
5. Pointers Expression (cont’d)
Example: An Illustration of Pointer Arithmetic
int i = 5, j = 10, int *ptr, **pptr; int i = 5, j = 10;
ptr = &i; pptr = &ptr; int *ptr, **pptr;
ptr = &i; pptr = &ptr;
cout<<*ptr++<<" "<<ptr<<endl;
cout<<*(ptr++)<<" “<<ptr<<endl; cout<<ptr+1<<endl;
cout<<ptr+2<<endl;
cout<<*++ptr<<" "<<ptr<<endl; cout<<ptr-1<<endl;
cout<<*(++ptr)<<" "<<ptr<<endl; cout<<ptr-3<<endl;
cout<<++*ptr<<" "<<ptr<<endl;
cout<<++(*ptr)<<" “<<ptr<<endl; Output ?
cout<<(*ptr)++<<" "<<ptr<<endl;
What
Note: Run each pairs is the
of cout output?
statements for
the program on the left hand and each of the
Output ? cout statements for the program on the right
58get
hand separately to 58similar
58 outputs .
Chapter 5 30
5. Pointers Expression (cont’d)
7.2 Pointers Comparison
Relational operators can be used to compare addresses in pointers.
Comparing addresses in pointers is not the same as comparing the values
pointed at by pointers.
Only pointer of the same types are comparable.
Chapter 5 33
6. Pointers and Constants (3/5)
(b) Pointer to Constant:
A pointer through which the value of the variable that the pointer points
cannot be changed.
The address of these pointers can be changed.
How to declare it?
Syntax: const <type of pointer>* <name of pointer>
//the below are invalid: neither the value nor address changed
ptr = &b; *ptr = 30;
return 0;
}
Chapter 5 35
6. Pointers and Constants (5/5)
Exercise 5.2:
Analyze the segment below and identify
Type of pointers
Invalid statements p2=&y;
*p2=100;
int x=10, y=20;
const int z=10; int * const p3= &x;
*p3=60;
int * p1=&x; p3=&y;
int *p1=20;
p1=&y; const int * const p4=&x;
Chapter 5 36
7. Pointers and Arrays
Basically the concept of array is very similar to the concept of pointer.
The identifier of an array actually a pointer that holds the address of the
first element (base address) of the array.
Therefore if you have two declarations : int a[10]; int* p;
then the assignment p = a; is perfectly valid
The only difference between the two is that the value of “p” can be
changed to any integer variable address whereas “a” will always point to
the integer array of length 10 defined.
Chapter 5 37
7. Pointers and Arrays (cont’d)
Differentiate between Array of Pointers & Pointers to Array
Chapter 5 38
7. Pointers and Arrays (cont’d)
Example 1:
(Printing 1D array elements address)
#include <iostream>
using namespace std;
int main (){
int arr[5];
cout<<"\nAddress of a[0]: "<<&arr[0];
cout<<"\nArray Name as pointer: "<<arr;
Note:
• Array names is
used as Pointers
Chapter 5 40
7. Pointers and Arrays (cont’d)
Example 2: Using a pointer notation to print array elements
// C++ Program to insert and display
// data entered by using pointer notation.
// Display data
cout << "Displaying data:\n ";
#include <iostream>
for (int i = 0; i < 5; ++i) {
using namespace std;
// display value of arr[i]
int main() {
cout << *(arr + i) << endl ;
float arr[5];
}
// Insert data
cout << "Enter 5 numbers: ";
return 0;
for (int i = 0; i < 5; ++i) {
}
// insert value to arr[i]
cin >> *(arr + i) ;
}
Chapter 5 41
7. Pointers and Arrays (cont’d)
Example 3: Manipulate array elements using an other pointer
#include <iostream>
using namespace std;
int main () {
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;
Chapter 5 43
7. Pointers and Arrays (cont’d)
Note
Consider the 2-D array declaration int arr[3][4],
Recall that
The name of an array is a constant pointer that points to the 1st elements
of 1-D array.
A pointer (array) can remember members of particular data group. i.e. arr
is an array of 3 elements where each element is a 1-D array of 4 integers.
Accordingly, in 2-D array the array identifier is pointing to the 1st row
(group of data elements)
i.e. the address of the 1st element of each row is used as a base address of
the respective row.
Hence, arr is a ‘pointer to an array of 4 integers’ and according to pointer
arithmetic the expression arr + 1 and arr + 2 will represent the address of
the 1st element of the 2nd and 3rd row respectively.
Chapter 5 44
7. Pointers and Arrays (cont’d)
In general,
arr = *arr = arr[0] = &arr[0][0]
arr+1 = *arr + 1 = (arr[0] + 1)
= (&arr[0][0] + 3 * 4bytes) = (arr[0] + 12 bytes)
Chapter 5 45
7. Pointers and Arrays (cont’d)
Example 1: using 2d Array name as a pointer notation
Chapter 5 46
7. Pointers and Arrays (cont’d)
Example 2: Manipulation 2-D Array elements using a pointer without
nested loop
#include <iostream>
using namespace std; The output looks
int main(){
int arr[3][4] = { { 10, 11, 12, 13 },
{ 20, 21, 22, 23 },
{ 30, 31, 32, 33 }};
Chapter 5 51
7. Pointer and Strings (Cont’d)
Advantages of String Pointer
Pointer to string can be used to declare a unnamed string.
No need to declare the size of string beforehand.
Makes more efficient use of available memory by consuming lesser
number of bytes to store the strings
Makes the manipulation of the strings much easier
Chapter 5 52
8. Pointers with Function
In a function pointer can be used
Function calling and parameter passing
Return multiple value from functions
Passing array to function conveniently
Function pointer (hold address of functions)
Chapter 5 53
8. Pointers with Function (cont’d)
Reference Variable Vs. Pointers
A reference variable is an additional name (alias – alternative name) to an
existing memory location.
Unlike a reference variable, pointers hold address of an other variable
Pointer: Reference:
x
int x=9;
9 x
int x= 9;
int *ref; 9
ref = &x; int &ref ; ref
ref ref = x;
Note:
Unlike a pointer, a reference variable always refers to the same object.
Assigning a reference variable with a new value actually changes the value
of the referred object.
Reference variables are commonly used for parameter passing to a function
Chapter 5 54
8. Pointers with Function (cont’d)
Comparison of Summary of parameter passing
Chapter 5 55
8. Pointers with Function (cont’d)
Comparison of Summary of parameter passing
PASS BYVALUE PASS BYREFERENCE PASS BYPOINTER
Separate memory is Formal and actual Formal parameters contain
allocated to formal parameters share the same the address of actual
parameters. memoryspace. parameters.
Changes done informal Changes done informal Changes done informal
parameters arenot parameters are parameters are
reflected in actual reflectedin actual reflectedin actual
parameters.9 parameters. parameters.
Foreg. Foreg. Foreg.
void cube(int x) {x= x*x*x; } void cube(int x) {x= x*x*x; } void cube(int x) {x= x*x*x; }
voidmain(){ voidmain(){ voidmain(){
int y=10; int y=10; int y=10;
cout<<y<<endl; cout<<y<<endl; cout<<y<<endl;
cube(y); cube(y); cube(y);
cout<<y<<endl;} cout<<y<<endl;} cout<<y<<endl;}
output: 1010 output: 101000 output: 101000
Chapter 5 56
8. Pointers with Function (cont’d)
Example 1: parameter passing by address
#include<iostream>
using namespace std;
int main(){
float weight, height, myIBM;
#include<iostream>
using namespace std; int main() {
float A[5] = {0.0, 3.0, 1.5, 2.0, 4.1};
float *findMax(float A[], int N) { float *maxA;
float *theMax = &(A[0]);
maxA = findMax(A,5);
for (int i = 1; i < N; i++){ cout<<"The Max is: "<<*maxA<<endl;
if (A[i] > *theMax)
theMax = &(A[i]); return 0;
} }
return theMax;
}
Chapter 5 58
8. Pointers with Function (cont’d)
Example 3: Pointer Return address
#include<iostream>
using namespace std; int main() {
float A[5] = {0.0, 3.0, 1.5, 2.0, 4.1};
float *findMax(float *A, int N) { float *maxA;
float theMax = A[0];
maxA = findMax(A,5);
for (int i = 1; i < N; i++){ //findMax(&A[0],5); is also possible
if (A[i] > theMax)
theMax = A[i]; cout<<"The Max is: "<<*maxA<<endl;
}
return &theMax; return 0;
} }
Chapter 5 59
8. Pointers with Function (cont’d)
Example 4: Return multiple value using pointer
Hot to return multiple
#include<iostream> value in function?
using namespace std; Array
void division(int a, int b, int* q, int* r) { Structure
*q = a/b; *r = a%b; Calling by reference
} Calling by address
int main(){
int quotient, reminder, x, y;
cout<<"Enter two numbers: "; cin>>x>>y;
Chapter 5 63
Activities (predict output and debugging error)
1. Find the output of the following program (c) Given the following lines
of codes,
(a)
int ival = 1024;
int a = 3;
int ival2 = 2048;
char s = 'z';
int* pi1 = &ival;
double d = 1.03;
int* pi2 = &ival2;
int *pa = &a;
int** pi3 = 0;
char *ps = &s;
double *pd = &d;
Are the following statements
cout << sizeof(pa) << sizeof(*pa)<< sizeof(&pa) << endl;
legal or illegal?
cout << sizeof(ps) << sizeof(*ps)<< sizeof(&ps) << endl;
(1) pi2 = *pi1;
cout << sizeof(pd) << sizeof(*pd)<< sizeof(&pd) << endl;
(2) ival = pi1;
(3) pi3 = &pi2;
(b)
int a[5] = {2,4,6,8,22};
(d) what is wrong?
int *p = &a[1];
int a = 58, *p = &a;
cout << a[0] << " "<< p[-1]<<“\n”;
int **q = &p;
COUT<< a[1] << " "<< p[0]<<endl;
int ***r = &q;
cout << a[2] << *(p+2)<<“\n”<< (a[4] = = *(p+3))<<endl;
q = &a;
s = &q; 64
Chapter 5
Activities (Short answer)
pointer).
Chapter 5 65
Practical Exercise
1) Write a program that declares and initializes three one-dimensional
arrays named price, quantity, and amount in the main(). Each array is
able to hold 10 double-precision numbers. Have your program pass
these three arrays to a function called extend(), which calculates the
elements in the amount array as the product of the equivalent elements
in the price and quantity arrays using pointers. After extend () has put
values in the amount array, display the values in the amount array from
within main() using for loop.
The numbers to be stored in price are 10.62, 14.89, 13.21, 16.55,
18.62, 9.47, 6.58, 18.32, 12.15, and 3.98.
The numbers to be stored in quantity are 4, 8.5, 6, 7.35, 9, 15.3, 3, 5.4,
2.9, and 4.8.
Chapter 5 66
Practical Exercise
2) Write a C++ function swap that takes the name of a 2D array,
num rows, num columns, and two values i and j and swap the
two rows i and j. All error checking must be done.
3) Write a function to find the largest and smallest of three numbers using
pointer.
Chapter 5 67
Reading Assignment
Pointers to functions
Purpose of pointer to functions
Chapter 5 68
Reading Resources/Materials
Chapter 9:
✔ Walter Savitch; Problem Solving With C++ [10th edition,
University of California, San Diego, 2018
Chapter 8:
✔ P. Deitel , H. Deitel; C++ how to program, 10th edition, Global
Edition (2017)
Chapter 12:
✔ Gary J. Bronson; C++ for Engineers and Scientists (3rdEdition),
2010 Course Technology, Cengage Learning
Chapter 5 69
Thank You
For Your Attention!!
70