0% found this document useful (0 votes)
5 views

Pointers Old

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Pointers Old

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

POINTERS

AND
DYNAMIC OBJECTS
Topics
Pointers
◦ Memory addresses
◦ Declaration
◦ Dereferencing a pointer
◦ Pointers to pointer

Static vs. dynamic objects


◦ new and delete
Computer Memory
Each variable is assigned a memory slot (the size depends on the data
type) and the variable’s data is stored there

emory address: 1020 1024 1032

… … 100 … 1024 …
a
Variable a’s value, i.e., 100, is
int a = 100; stored at memory location 1024
Pointers
A pointer is a variable used to store the address of a memory cell.
We can use the pointer to reference this memory cell

Memory address: 1020 1024 1032

… … 100 … 1024 …
integer
pointer
Pointer Types
Pointer
◦ C++ has pointer types for each type of object
◦ Pointers to int objects
◦ Pointers to char objects
◦ Pointers to user-defined objects
(e.g., RationalNumber)
◦ Even pointers to pointers
◦ Pointers to pointers to int objects
Pointer Variable
Declaration of Pointer variables
type* pointer_name;
//or
type *pointer_name;
where type is the type of data pointed to (e.g. int, char, double)

Examples:
int *n;
RationalNumber *r;
int **p; // pointer to pointer
Address Operator &
The "address of " operator (&) gives the memory address of the
variable
◦ Usage: &variable_name
Memory address: 1020 1024

… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
Address Operator &
Memory address: 1020 1024 1032

… 88 100 … … …
a b
#include <iostream>
using namespace std;
 Result is:
void main(){ The address of a is: 1020
int a, b; The address of b is: 1024
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}
Pointer Variables

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;  Result is:
int *p = &a; 100 1024
cout << a << " " << &a <<endl; 1024 1032
cout << p << " " << &p <<endl;

The value of pointer p is the address of variable a


A pointer is also a variable, so it has its own memory address
Pointer to Pointer

What is the output?

58 58 58
Dereferencing Operator
*
We can access to the value stored in the variable pointed to by using the
dereferencing operator (*),

Memory address: 1020 1024 1032

… 88 100 … 1024 …
a p
int a = 100;
 Result is:
int *p = &a;
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
Don’t get confused
Declaring a pointer means only that it is a pointer: int *p;
Don’t be confused with the dereferencing operator, which is also
written with an asterisk (*). They are simply two different tasks
represented with the same sign
int a = 100, b = 88, c = 8;
int *p1 = &a, *p2, *p3 = &c;
p2 = &b; // p2 points to b
p2 = p1; // p2 points to a  Result is:
b = *p3; //assign c to b 888
*p2 = *p3; //assign c to a
cout << a << b << c;
A Pointer Example

Memory Layout
The code
Box diagram
main
void doubleIt(int x,
int * p) p
a 16 8192
{ (8200)
*p = 2 * x;
doubleIt
x 9
} (8196)
int main(int argc, const
char * argv[]) a 16 main
{
doubleIt (8192)
int a = 16;
x 9
doubleIt(9, &a);

a gets 18
return 0;
p
}
Another Pointer
Example
#include <iostream> Let’s figure out: 
using namespace std; value1==? / value2==?
int main (){
Also, p1=? p2=?
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value // pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}
Another Pointer
Example
int a = 3;
char s = ‘z’;
double d = 1.03;
int *pa = &a;
char *ps = &s;
double *pd = &d;
% sizeof returns the # of bytes…
cout << sizeof(pa) << sizeof(*pa)
<< sizeof(&pa) << endl;
cout << sizeof(ps) << sizeof(*ps)
<< sizeof(&ps) << endl;
cout << sizeof(pd) << sizeof(*pd)
<< sizeof(&pd) << endl;
Traditional Pointer
Usage
void IndirectSwap(char *Ptr1, char *Ptr2){
char temp = *Ptr1;
*Ptr1 = *Ptr2;
*Ptr2 = temp;
}
int main() {
char a = 'y';
char b = 'n';
IndirectSwap(&a, &b);
cout << a << b << endl;
return 0;
}
Pass by Reference
void IndirectSwap(char& y, char& z) {
char temp = y;
y = z;
z = temp;
}
int main() {
char a = 'y';
char b = 'n';
IndirectSwap(a, b);
cout << a << b << endl;
return 0;
}
Pointers and Arrays
 The name of an array points only to the first
element not the whole array.

1000

1004

1008

1012

1016
Array Name is a pointer constant
#include <iostream>
using namespace std;

void main (){


int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;
}

Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
Dereferencing An Array Name

This element is
called a[0] or
*a
#include <iostream>
a[0] 2 using namespace std;
a void main(){
a[1] 4 int a[5] = {2,4,6,8,22};
a[2] 6 cout << *a << " "
<< a[0];
a[3] 8 } //main
a[4] 22
a
Array Names as Pointers
 To access an array, any pointer to the first element
can be used instead of the name of the array.

We could replace *p by *a

#include <iostream>
a p using namespace std;
void main(){
a[0] 2 int a[5] = {2,4,6,8,22};
22
a[1] 4 int *p = a;
a[2] 6 cout << a[0] << " "
a[3] 8 << *p;
a[4] 22 }
a
Multiple Array Pointers
 Both a and p are pointers to the same array.

#include <iostream>
a[0] using namespace std;
a[0] 22 void main(){
2 p
44 int a[5] = {2,4,6,8,22};
a[1] 4 int *p = &a[1];
a[2] 6 cout << a[0] << " "
<< p[-1];
a[3] 8 p[0]
cout << a[1] << " "
a[4] 22 << p[0];
}
Pointer Arithmetic
 Given a pointer p, p+n refers to the element that
is offset from p by n positions.

a 2 p - 1

a + 1 4 p
a + 2 6 p + 1
a + 3 8 p + 2
a + 4 22 p + 3
Dereferencing Array Pointers

a[0] or *(a + 0) 2 a
a[1] or *(a + 1) 4 a + 1
a[2] or *(a + 2) 6 a + 2
a[3] or *(a + 3) 8 a + 3
a[4] or *(a + 4) 22 a + 4

*(a+n) is identical to a[n]


 Note: flexible pointer syntax
Array of Pointers & Pointers to Array
a
p
b
c

An array of Pointers A pointer to an array


int a = 1, b = 2, c = 3; int list[5] = {9, 8, 7, 6, 5};
int *p[5]; int *p;
p[0] = &a; P = list;//points to 1st entry
p[1] = &b; P = &list[0];//points to 1st entry
p[2] = &c; P = &list[1];//points to 2nd entry
P = list + 1; //points to 2nd entry
NULL pointer
NULL is a special value that indicates an empty pointer
If you try to access a NULL pointer, you will get an error
int *p;
p = 0;
cout << p << endl; //prints 0
cout << &p << endl;//prints address of p
cout << *p << endl;//Error!
Storing 2D Array in 1D
Array
int twod[3][4] = {{0,1,2,3}, {4,5,6,7},
{8,9,10,11}};

int oned[12];
for(int i=0; i<3; i++){
for(int j=0; j<4 ; j++)
oned[i*4+j] = twod[i][j];
}
Pointer to 2-Dimensional Arrays
table table[i] =
&table[i][0]
refers to
table + 1 table[ 0] or *( table + 0 ) the address
of the ith
row
table + 2 table[ 1] or *( table + 1 )

table[ 2] or *( table + 2 )
int table[3][4] = {{1,2,3,4}, *(table[i]+j)
What is = table[i][j]
{5,6,7,8},{9,10,11,12}};
**table
? for(int i=0; i<3; i++){
for(int j=0; j<4; j++)
cout << *(*(table+i)+j);
cout << endl;
}
DYNAMI
C
OBJECTS
Memory Management
Static Memory Allocation
◦ Memory is allocated at compilation time

Dynamic Memory
◦ Memory is allocated at running time
Static vs. Dynamic
Objects
Static object Dynamic object

(variables as declared in function calls) Memory is acquired by program with


Memory is acquired automatically an allocation request
new operation

Memory is returned automatically Dynamic objects can exist beyond


when object goes out of scope the function in which they were
allocated

Object memory is returned by a


deallocation request
delete operation
Memory Allocation

new
delete

{ int* ptr;
int a[200]; ptr = new int[200];
… …
} delete [] ptr;
Object (variable) creation:
New
Syntax
ptr = new SomeType;

where ptr is a pointer of type SomeType

Example
int* p = new int;

Uninitialized int variable

p
Object (variable) destruction: Delete

Syntax
delete p;
storage pointed to by p is returned to free store and p is now
undefined

Example
int* p = new int;
*p = 10;
delete p;

p 10
Array of New:
dynamic arrays
Syntax
P = new SomeType[Expression];
◦ Where
◦ P is a pointer of type SomeType
◦ Expression is the number of objects to be constructed -- we are making an array

Because of the flexible pointer syntax, P can be considered to be an array


Example
Dynamic Memory Allocation
 Request for “unnamed” memory from the Operating System

new
 int *p, n=10; p
p = new int;

new
p = new int[100];
p
new

p = new int[n]; p
Memory Allocation Example
Want an array of unknown size
#include <iostream>
using namespace std;
void main()
{
int n;
cout << “How many students? “;
cin >> n;
int *grades = new int[n];
for(int i=0; i < n; i++){
int mark;
cout << “Input Grade for Student” << (i+1) << “ ? :”;
cin >> mark;
grades[i] = mark;
}
. . .
printMean( grades, n ); // call a function with dynamic array
. . .
}
Freeing (or deleting) Memory
Dangling Pointer Problem
int *A = new int[5];
for(int i=0; i<5; i++)
A[i] = i;
int *B = A;
A
0 1 2 3 4
B

delete [] A;
Locations do not belong to program
B[0] = 1; // illegal!
A —

?
B
Memory Leak Problem
int *A = new int [5];
for(int i=0; i<5; i++)
A[i] = i;
A 0 1 2 2 3 4

These locations cannot be


A = new int [5]; accessed by program

A 0 1 2 3 4

— — — — —
A Dynamic 2D Array
 A dynamic array is table
an array of pointers 32 18 12 24
to save space when table[0]
not all rows of the table[1] 13 11 16 12 42 19 14
array are full. table[2]
22
table[3]
 int **table; table[4] 13 13 14
table[5]
11 18
table = new int*[6];

table[0] = new int[4];
table[1] = new int[7];
table[2] = new int[1];
table[3] = new int[3];
table[4] = new int[2];
table[5] = NULL;
Memory Allocation
int **table;

table = new int*[6];

table[0]= new int[3];


table[1]= new int[1];
table[2]= new int[5];
table[3]= new int[10];
table[4]= new int[2];
table[5]= new int[6];

table[0][0] = 1; table[0][1] = 2; table[0][2] = 3;


table[1][0] = 4;
table[2][0] = 5; table[2][1] = 6; table[2][2] = 7; table[2][3] = 8; table[2]
[4] = 9;

table[4][0] = 10; table[4][1] = 11;


cout << table[2][5] << endl;
Memory Deallocation
Memory leak is a serious bug!
Each row must be deleted individually
Be careful to delete each row before deleting the table pointer.
◦ for(int i=0; i<6; i++)
delete [ ] table[i];
delete [ ] table;
Create a matrix of any dimensions, m by n:

Put it into a function:

nt m, n; int m, n;
cin >> m >> n >> endl;
in >> m >> n >> endl;
int** mat;
mat = imatrix(m,n);
nt** mat; …

at = new int*[m]; int** imatrix(nr, nc) {


int** m;
m = new int*[nr];
or (int i=0;i<m;i++) for (int i=0;i<nr;i++)
mat[i] = new int[n]; m[i] = new int[nc];
return m;
}
Pointers to objects
Pointers to objects
Any type that can be used to declare a
variable/object can also have a pointer type.
Consider the following class:
class Rational
{
private:
int numerator;
int denominator;
public:
Rational(int n, int d);
void Display();
};

CSC2110 - DATA STRUCTURES/ALGORITHMS 49


Pointers to objects
(Cont..)
Rational *rp = NULL; rp FFF0 0
Rational r(3,4); FFF1
rp = &r; FFF2
FFF3
FFF4
FFF5
FFF6
FFF7
FFF8
FFF9
FFFA
FFFB
FFFC
FFFD
CSC2110 - DATA STRUCTURES/ALGORITHMS 50
Pointers to objects
(Cont..)
Rational *rp = NULL; rp FFF0 0
Rational r(3,4); FFF1
rp = &r; FFF2
FFF3
FFF4 3
FFF5
FFF6
FFF7
numerator = r FFF8 4
3
denominator FFF9
=4 FFFA
FFFB
FFFC
FFFD
CSC2110 - DATA STRUCTURES/ALGORITHMS 51
Pointers to objects
(Cont..)
Rational *rp = NULL; rp FFF0 FFF4
Rational r(3,4); FFF1
rp = &r; FFF2
FFF3
FFF4 3
FFF5
FFF6
FFF7
numerator = r FFF8 4
3
denominator FFF9
=4 FFFA
FFFB
FFFC
FFFD
CSC2110 - DATA STRUCTURES/ALGORITHMS 52
Pointers to objects
(Cont..)
If rp is a pointer to an object, then two notations can be used to
reference the instance/object rp points to.
Using the de-referencing operator *
(*rp).Display();

Using the member access operator ->


rp -> Display();

CSC2110 - DATA STRUCTURES/ALGORITHMS 53


Dynamic Allocation of a Class
Object
Consider the Rational class defined before

Rational *rp;
int a, b;
cin >> a >> b;
rp = new Rational(a,b);
(*rp).Display(); // rp->Display();
delete rp;
rp = NULL;

CSC2110 - DATA STRUCTURES/ALGORITHMS 54

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy