You are on page 1of 45

Pointers and Dynamic Objects

Presented By:-
Sumit Kumar Nager
PGT Computer Science

PGT Computer Science Created By Sumit Kumar Nager 1


Contents
Pointer Dynamic Objects
• Computer Memory • Memory Management
• Pointer Basic • Memory Allocation
• Why Pointer • Static Vs Dynamic Memory
• Address (&) and De-reference(*) Allocation
Operator • New Operator
• Reference Variable • Delete Operator
• Pass by Reference • Dangling Pointer Problem
• Pointer and Array • Memory Leak Problem
• Pointer Arithmetic • Memory De-allocation
• Null Pointer

PGT Computer Science Created By Sumit Kumar Nager 2


Pointer
Pointing to the plane

Pointer of the plane

PGT Computer Science Created By Sumit Kumar Nager 3


Pointers
• Point to here, point to there, point to that, point to this, and point to
nothing!

• well, they are just memory addresses!!??

PGT Computer Science Created By Sumit Kumar Nager 4


Computer Memory
• When declaring a variable, the compiler sets aside memory storage with a
unique address to store that variable.
• The compiler associates that address with the variable’s name.
• When the program uses the variable name, it automatically accesses a
proper memory location.
• No need to concern which address.
• Each variable is assigned a memory slot (the size depends on the data
type) and the variable’s data is stored there

Memory address: 1020 1024

… … 100 … … …
a Variable a’s value, i.e., 100, is
int a = 100; stored at memory location 1024

PGT Computer Science Created By Sumit Kumar Nager 5


Pointer
• A pointer is a variable used to store the address of a memory cell.
• We can use the pointer to reference the memory cell

Int a,*p;
a= 100;
p=&a;

Memory address: 1020 1024 1032

… … 100 … 1024 …

integer
pointer

PGT Computer Science Created By Sumit Kumar Nager 6


Why Pointer
• By using pointers, it is an efficient way of accessing and manipulating
data.
• Very useful for dynamic memory management, as we know memory,
registers and cache are scarce resource in computer system.
• Every computer system, there are fixed and limited amount of memory for
temporary data storage and processing.
• There are loading and unloading data into and from, moving data from
and to different locations of the memory, including the cache and the
processors’ registers for temporary data storage and processing.
• The loading and unloading need an efficient memory management.
• Some of the memory portion also used for shared data to further
optimizes the utilization.
• This shared data access (read/write) depends heavily on the pointers
manipulation.
• Without moving/loading/unloading data to/from different locations in
memory, we can use pointers to point to different locations.
PGT Computer Science Created By Sumit Kumar Nager 7
Pointers and Simple Variables
• A pointer is a numeric variable and like other variables, must be declared
and initialized before it can be used.
• The following is a general form for declaring a pointer variable,

• type_of_stored_data    * pointer_variable_name;

• For example,

• char*    chName;
• int   *    nTypeOfCar;
• float    *fValue;

• type_of_stored_data is any valid pointer base type such as char, int, float or
other valid C derived types such as array and struct.
• It indicates the type of the variable’s data to which the pointer is pointed to.
• The pointer_variable_name follows the same rules as other C variable
naming convention and must be unique.
PGT Computer Science Created By Sumit Kumar Nager 8
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

PGT Computer Science Created By Sumit Kumar Nager 9


Address Operator &
Memory address: 1020 1024 1032

… 88 100 … … …
#include <iostream> a b
using namespace std;
void main()
Result is:
{ int a, b; The address of a is:1020
a = 88; The address of b is:1024

b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}
PGT Computer Science Created By Sumit Kumar Nager 10
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

PGT Computer Science Created By Sumit Kumar Nager 11


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;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
1024 100
cout << p << " " << *p << endl; 1032
cout << &p << endl;
PGT Computer Science Created By Sumit Kumar Nager 12
Pointer to Pointer

What is the output?

58 58 58

PGT Computer Science Created By Sumit Kumar Nager 13


A Pointer Example
The code Box diagram Memory Layout
main
void doubleIt(int x, int * p)
{ a 16
p 8192
*p = 2 * x;
(8200)
} doubleIt
int main()
x 9
{
(8196)
int a = 16;
doubleIt(9, &a); a
doubleIt 16 main
return 0; (8192)
} x 9

a gets 18 p

PGT Computer Science Created By Sumit Kumar Nager 14


Another Pointer Example
#include <iostream>
using namespace std; Let’s figure out:
int main () value1==?
{ value2==?
int value1 = 5, value2 = 15; Also, p1=?
int *p1, *p2; p2=?
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2 value1==10
*p1 = 10; // value pointed to by p1=10 value2==20
*p2 = *p1; // value pointed to by p2= value p1=20
//pointed to by p1 p2=20
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20

cout << "value1==" << value1 << "/ value2==" << value2<<endl;
cout<<*p1<<“ ”<<*p2;
return 0;
}
PGT Computer Science Created By Sumit Kumar Nager 15
Reference Variables
A reference is an additional name to an existing
memory location
Pointer: Reference:

x 9 x 9
ref
ref
int x = 9;
int x=9;
int &ref = x;
int *ref;
ref = &x;
PGT Computer Science Created By Sumit Kumar Nager 16
Reference Variables
• 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

PGT Computer Science Created By Sumit Kumar Nager 17


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;
}
PGT Computer Science Created By Sumit Kumar Nager 18
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;
PGT Computer Science
} Created By Sumit Kumar Nager 19
Pointers and Arrays
The name of an array points only to the first
element not the whole array.

1000

1004

1008

1012

1016

PGT Computer Science Created By Sumit Kumar Nager 20


Array Name is a pointer constant
#include <iostream>
using namespace std;
int main ()
{ int a[5];
cout << "Address of a[0]: " << &a[0] << endl<< "Name as
pointer: " << a << endl;
return 0;
}

Output:
Address of a[0]: 0x22feec
Name as pointer: 0x22feec
PGT Computer Science Created By Sumit Kumar Nager 21
Dereferencing An Array Name
This element is called a[0] or *a

a[0] 2 #include <iostream>


a[1] 4 using namespace std;
a[2] 6 a int main()
8 { int a[5] = {2,4,6,8,22};
a[3]
cout << *a << " " <<
a[4] 22 a[0];
a return 0;
} //main
PGT Computer Science Created By Sumit Kumar Nager 22
Array Names as Pointers
To access an array, any pointer to the first element
can be used instead of the name of the array.
#include <iostream>
a using namespace std;
P Int main()
a[0] 2 { int a[5] =
a[1] 4 {2,4,6,8,22};
a[2] 6
int *p = a;
a[3] 8
a[4] 22 cout << a[0] << " "
a << *p;
return 0;
We could replace *p by *a
PGT Computer Science Created By Sumit Kumar Nager} 23
Multiple Array Pointers
Both a and p are pointers to the same array.

#include <iostream>
a[0]
22 using namespace std;
a[0] 2 44
int main()
a[1] 4 p { int a[5] = {2,4,6,8,22};
a[2] 6 int *p = &a[1];
a[3] 8
p[0]
cout << a[0] << " " << p[-1];
a[4] 22 cout << a[1] << " " << p[0];
return 0;
}

PGT Computer Science Created By Sumit Kumar Nager 24


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
PGT Computer Science Created By Sumit Kumar Nager 25
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

PGT Computer Science Created By Sumit Kumar Nager 26


Array of Pointers & Pointers to Array
a
p
b
c
p

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
PGT Computer Science Created By P = Kumar
Sumit list Nager
+ 1; //points to 2nd entry
27
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!

PGT Computer Science Created By Sumit Kumar Nager 28


POINTERS
• The following table summarizes pointer operations.
Operation Description
You can assign a value to a pointer.  The value
1. Assignment should be an address with the address-of-
(=) operator (&) or from a pointer constant (array
name)
The indirection operator (*) gives the value
2. Indirection (*)
stored in the pointed to location.
You can use the address-of operator to find the
3. Address of (&) address of a pointer, so you can use pointers to
pointers.

PGT Computer Science Created By Sumit Kumar Nager 29


POINTERS
• The following table summarizes pointer operations.

Operation Description
You can add an integer to a pointer to
4. Incrementing
point to a different memory location.
You can subtract an integer from a
5. Differencing pointer to point to a different memory
location.
Valid only with two pointers that point
6. Comparison
to the same array.
PGT Computer Science Created By Sumit Kumar Nager 30
Fun Program
#include<stdio.h> #include<iostream>
int main() using namespace std;
{ int i=327; int main()
char *p=&i; { int i=327;
*++p=2; char *p=&i;
printf("%d", i); *++p=2;
return 0; cout<<i;
} return 0;
}

Output : 583 Output : Error cannot convert


int* to char*
PGT Computer Science Created By Sumit Kumar Nager 31
Dynamic
Objects

PGT Computer Science Created By Sumit Kumar Nager 32


Memory Management
• Static Memory Allocation
– Memory is allocated at compilation time
• Dynamic Memory
– Memory is allocated at running time

PGT Computer Science Created By Sumit Kumar Nager 33


Static vs. Dynamic Objects
• Static object • Dynamic object
(variables as declared in – Memory is acquired by
function calls) program with an
– Memory is acquired allocation request
automatically • new operation
– Memory is returned – Dynamic objects can
automatically when exist beyond the
object goes out of function in which they
scope were allocated
– Object memory is
returned by a
deallocation request
PGT Computer Science Created By Sumit Kumar Nager • delete operation 34
Memory Allocation

new
delete

int* ptr;
{
ptr = new int[200];
int a[200];


delete [] ptr;
}

PGT Computer Science Created By Sumit Kumar Nager 35


Object (variable) creation: New
Syntax
ptr = new SomeType;
where ptr is a pointer of type SomeType
Example
int* p = new int;
Uninitialized int variable

PGT Computer Science Created By Sumit Kumar Nager 36


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

PGT Computer Science Created By Sumit Kumar Nager 37


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

PGT Computer Science Created By Sumit Kumar Nager 38


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
PGT Computer Science Created By Sumit Kumar Nager 39
Freeing (or deleting) Memory

PGT Computer Science Created By Sumit Kumar Nager 40


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;
B[0] = 1; // illegal! Locations do not belong to the program
A
?
B

PGT Computer Science Created By Sumit Kumar Nager 41


Memory Leak Problem

int *A = new int [5];


for(int i=0; i<5; i++)
A[i] = i; 0 2
A 1 2 3 4

A = new int [5]; These Locations cannot be


accessedA by the program
0 1 2 3 4

-- -- -- -- --
PGT Computer Science Created By Sumit Kumar Nager 42
Memory De-allocation

• 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;

PGT Computer Science Created By Sumit Kumar Nager 43


References
• http://www.cplusplus.com/doc/tutorial/pointers/
• http://www.cprogramming.com/tutorial/lesson6.html
• http://en.wikipedia.org/wiki/Pointer_%28computer_programming%29
• http://www.cppforschool.com/tutorial/pointer.html
• http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&ved=0CD
YQFjAD&url=http%3A%2F%2Fdigital.cs.usu.edu%2F~watson%2Fcs1410%2Fnotes%
2Fch9.ppt&ei=SuoVVPK6IpaiugSi5IKIAw&usg=AFQjCNGKj5OApMsU1ynVaNwrn7YS
r8lnBw&sig2=hzqHqd5-nhSA0LODYHIm_Q
• http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMemb
er-Function.htm
• Object Oriented Programming With C++ - Balagurusamy, herbert
• Fundamentals of Data Structures by Ellis Horowitz and Sartaj Sahni
• C++ Complete Reference.

PGT Computer Science Created By Sumit Kumar Nager 44


END
PGT Computer Science Created By Sumit Kumar Nager 45

You might also like