SlideShare una empresa de Scribd logo
1 de 55
Pointers
and
dynamic objects
COMP171
Fall 2005
Pointers and dynamic objects/ Slide 2
Topics
Pointers
Memory addresses
Declaration
Dereferencing a pointer
Pointers to pointer
Static vs. dynamic objects
new and delete
Pointers and dynamic objects/ Slide 3
Computer Memory
Each variable is assigned a memory slot (the
size depends on the data type) and the
variable’s data is stored there
Variable a’s value, i.e., 100, is
stored at memory location 1024
100100…… …… 10241024 ……
emory address: 1024 1032
int a = 100;
……
1020
a
Pointers and dynamic objects/ Slide 4
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
100100…… …… 10241024 ……
Memory address: 1024 1032
……
1020
integer
pointer
Pointers and dynamic objects/ Slide 5
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
Pointers and dynamic objects/ Slide 6
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
Pointers and dynamic objects/ Slide 7
Address Operator &
The "address of " operator (&) gives the memory
address of the variable
Usage: &variable_name
100100…… …… …… ……
Memory address: 1024
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
……
1020
a
Pointers and dynamic objects/ Slide 8
Address Operator &
1001008888 …… …… ……
Memory address: 1024 1032
a
……
1020
b
#include <iostream>
using namespace std;
void main(){
int a, b;
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}
Result is:
The address of a is: 1020
The address of b is: 1024
Pointers and dynamic objects/ Slide 9
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 Variables
1001008888 …… 10241024 ……
Memory address: 1024 1032
……
1020
a p
int a = 100;
int *p = &a;
cout << a << " " << &a <<endl;
cout << p << " " << &p <<endl;
Result is:
100 1024
1024 1032
Pointers and dynamic objects/ Slide 10
Pointer to Pointer
What is the output?
58 58 58
Pointers and dynamic objects/ Slide 11
Dereferencing Operator *
We can access to the value stored in the variable
pointed to by using the dereferencing operator (*),
1001008888 …… 10241024 ……
Memory address: 1024 1032
……
1020
int a = 100;
int *p = &a;
cout << a << endl;
cout << &a << endl;
cout << p << " " << *p << endl;
cout << &p << endl;
Result is:
100
1024
1024 100
1032
a p
Pointers and dynamic objects/ Slide 12
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
b = *p3; //assign c to b
*p2 = *p3; //assign c to a
cout << a << b << c;
Result is:
888
Pointers and dynamic objects/ Slide 13
A Pointer Example
The code
void doubleIt(int x,
int * p)
{
*p = 2 * x;
}
int main(int argc, const
char * argv[])
{
int a = 16;
doubleIt(9, &a);
return 0;
}
Box diagram
Memory Layout
9x
p
(8200)
x
(8196)
16a
main
doubleIt
p
a
(8192)
16
9
8192
main
doubleIt
a gets 18
Pointers and dynamic objects/ Slide 14
Another Pointer Example
#include <iostream>
using namespace std;
int main (){
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;
}
Result is
value1==10 / value2==20
Pointers and dynamic objects/ Slide 15
Another Pointer Example
int a = 3;
char s = ‘z’;
double d = 1.03;
int *pa = &a;
char *ps = &s;
double *pd = &d;
cout << sizeof(pa) << sizeof(*pa)
<< sizeof(&pa) << endl;
cout << sizeof(ps) << sizeof(*ps)
<< sizeof(&ps) << endl;
cout << sizeof(pd) << sizeof(*pd)
<< sizeof(&pd) << endl;
Pointers and dynamic objects/ Slide 16
Reference Variables
A reference is an additional name to
an existing memory location
9x
ref
Pointer:
9
x
ref
Reference:
int x=9;
int *ref;
ref = &x;
int x = 9;
int &ref = x;
Pointers and dynamic objects/ Slide 17
Reference Variables
A reference variable serves as an alternative name for
an object
int m = 10;
int &j = m; // j is a reference variable
cout << “value of m = “ << m << endl;
//print 10
j = 18;
cout << “value of m = “ << m << endl;
// print 18
Pointers and dynamic objects/ Slide 18
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
Pointers and dynamic objects/ Slide 19
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;
}
Pointers and dynamic objects/ Slide 20
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 dynamic objects/ Slide 21
Pointers and Arrays
The name of an array points only to the first
element not the whole array.
1000
1012
1016
1004
1008
Pointers and dynamic objects/ Slide 22
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
Pointers and dynamic objects/ Slide 23
Dereferencing An Array Name
#include <iostream>
using namespace std;
void main(){
int a[5] = {2,4,6,8,22};
cout << *a << " "
<< a[0];
} //main
2
4
8
6
22a[4]
a[0]
a[2]
a[1]
a[3]
a
a
This element is
called a[0] or
*a
Pointers and dynamic objects/ Slide 24
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
2 2
#include <iostream>
using namespace std;
void main(){
int a[5] = {2,4,6,8,22};
int *p = a;
cout << a[0] << " "
<< *p;
}
2
4
8
6
22a[4]
a[0]
a[2]
a[1]
a[3]
a p
a
Pointers and dynamic objects/ Slide 25
Multiple Array Pointers
Both a and p are pointers to the same array.
2 2
4 4
#include <iostream>
using namespace std;
void main(){
int a[5] = {2,4,6,8,22};
int *p = &a[1];
cout << a[0] << " "
<< p[-1];
cout << a[1] << " "
<< p[0];
}
2
4
8
6
22a[4]
a[0]
a[2]
a[1]
a[3]
p
p[0]
a[0]
Pointers and dynamic objects/ Slide 26
Pointer Arithmetic
Given a pointer p, p+n refers to the element that
is offset from p by n positions.
2
4
8
6
22
a
a + 2
a + 4
a + 3
a + 1 p
p + 2
p + 3
p - 1
p + 1
Pointers and dynamic objects/ Slide 27
*(a+n) is identical to a[n]
Dereferencing Array Pointers
2
4
8
6
22
a
a + 2
a + 4
a + 3
a + 1
a[3] or *(a + 3)
a[2] or *(a + 2)
a[1] or *(a + 1)
a[0] or *(a + 0)
a[4] or *(a + 4)
Note: flexible pointer syntax
Pointers and dynamic objects/ Slide 28
Array of Pointers & Pointers to Array
a
b
c
An array of Pointers
p
int a = 1, b = 2, c = 3;
int *p[5];
p[0] = &a;
p[1] = &b;
p[2] = &c;
int list[5] = {9, 8, 7, 6, 5};
int *p;
P = list;//points to 1st
entry
P = &list[0];//points to 1st
entry
P = &list[1];//points to 2nd
entry
P = list + 1; //points to 2nd
entry
A pointer to an array
Pointers and dynamic objects/ Slide 29
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!
Pointers and dynamic objects/ Slide 30
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];
}
Pointers and dynamic objects/ Slide 31
Pointer to 2-Dimensional Arrays
table[ 0] or *( table + 0 )
table
table[ 1] or *( table + 1 )
table + 1
table[ 2] or *( table + 2 )
table + 2
int table[3][4] = {{1,2,3,4},
{5,6,7,8},{9,10,11,12}};
for(int i=0; i<3; i++){
for(int j=0; j<4; j++)
cout << *(*(table+i)+j);
cout << endl;
}
*(table[i]+j)
= table[i][j]What is
**table
?
table[i] =
&table[i][0]
refers to
the address
of the ith
row
Dynamic
Objects
Pointers and dynamic objects/ Slide 33
Memory Management
Static Memory Allocation
Memory is allocated at compilation time
Dynamic Memory
Memory is allocated at running time
Pointers and dynamic objects/ Slide 34
Static vs. Dynamic Objects
Static object
(variables as declared in function calls)
Memory is acquired
automatically
Memory is returned
automatically when object
goes out of scope
Dynamic object
Memory is acquired by
program with an allocation
request
 new operation
Dynamic objects can exist
beyond the function in which
they were allocated
Object memory is returned
by a deallocation request
 delete operation
Pointers and dynamic objects/ Slide 35
Memory Allocation
{
int a[200];
…
}
int* ptr;
ptr = new int[200];
…
delete [] ptr;
new
delete
Pointers and dynamic objects/ Slide 36
Object (variable) creation: New
Syntax
ptr = new SomeType;
where ptr is a pointer of type SomeType
p
Uninitialized int variable
Example
int* p = new int;
Pointers and dynamic objects/ Slide 37
Object (variable) destruction:
Delete
Syntax
delete p;
storage pointed to by p is returned to free store and p is now
undefined
p
Example
int* p = new int;
*p = 10;
delete p;
10
Pointers and dynamic objects/ Slide 38
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
Pointers and dynamic objects/ Slide 39
Example
Dynamic Memory Allocation
Request for “unnamed” memory from the Operating System
int *p, n=10;
p = new int;
p = new int[100];
p
new
p
new
p = new int[n]; p
new
Pointers and dynamic objects/ Slide 40
Memory Allocation Example
Want an array of unknown size
main()
{
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
. . .
}
Pointers and dynamic objects/ Slide 41
Freeing (or deleting) Memory
Pointers and dynamic objects/ Slide 42
A Simple Dynamic List Example
cout << "Enter list size: ";
int n;
cin >> n;
int *A = new int[n];
if(n<=0){
cout << "bad size" << endl;
return 0;
}
initialize(A, n, 0); // initialize the array A with value 0
print(A, n);
A = addElement(A,n,5); //add an element of value 5 at the end of A
print(A, n);
A = deleteFirst(A,n); // delete the first element from A
print(A, n);
selectionSort(A, n); // sort the array (not shown)
print(A, n);
delete [] A;
Pointers and dynamic objects/ Slide 43
Initialize
void initialize(int list[], int size, int value){
for(int i=0; i<size; i++)
list[i] = value;
}
Pointers and dynamic objects/ Slide 44
print()
void print(int list[], int size) {
cout << "[ ";
for(int i=0; i<size; i++)
cout << list[i] << " ";
cout << "]" << endl;
}
Pointers and dynamic objects/ Slide 45
Adding Elements
// for adding a new element to end of array
int* addElement(int list[], int& size, int value){
int* newList = new int [size+1]; // make new array
if(newList==0){
cout << "Memory allocation error for addElement!" << endl;
exit(-1);
}
for(int i=0; i<size; i++)
newList[i] = list[i];
if(size) delete [] list;
newList[size] = value;
size++;
return newList;
}
Pointers and dynamic objects/ Slide 46
Delete the first element
// for deleting the first element of the array
int* deleteFirst(int list[], int& size){
if(size <= 1){
if( size) delete list;
size = 0;
return NULL;
}
int* newList = new int [size-1]; // make new array
if(newList==0){
cout << "Memory allocation error for deleteFirst!" << endl;
exit(-1);
}
for(int i=0; i<size-1; i++) // copy and delete old array
newList[i] = list[i+1];
delete [] list;
size--;
return newList;
}
Pointers and dynamic objects/ Slide 47
Adding Element (version 2)
// for adding a new element to end of array
void addElement( int * & list, int & size, const int value ){
int * newList = new int [size + 1];
if( newList == NULL ){
cout << "Memory allocation error for addElement!" << endl;
exit(-1);
}
for( int i = 0; i < size; i++ )
newList[ i ] = list[ i ];
if( size ) delete [] list;
newList[ size ] = value;
size++;
list = newList;
return;
}
Pointers and dynamic objects/ Slide 48
Deleting Element (version 2)
void deleteFirst( int * & list, int & size ){
if( size <= 1 ){
if( size )
delete list;
list = NULL;
size = 0;
return;
}
delete list; // delete the first element
list++;
size--;
return;
}
Pointers and dynamic objects/ Slide 49
Another Main program
int main(){
int * A = NULL;
int size = 0;
int i;
for( i = 0; i < 10; i++ )
addElement( A, size, i );
for( i = 0; i < 10; i++ )
cout << A[i] << " ";
cout << endl;
for( i = 0; i < 4; i++ )
deleteFirst( A, size );
for( i = 0; i < 6; i++ )
cout << A[i] << " ";
cout << endl;
return 0;
}
0 1 2 3 4 5 6 7 8 9
4 5 6 7 8 9
Pointers and dynamic objects/ Slide 50
Dangling Pointer Problem
int *A = new int[5];
for(int i=0; i<5; i++)
A[i] = i;
int *B = A;
delete [] A;
B[0] = 1; // illegal!
A
B
0 1 2 3 4
A
B
Locationsdonotbelongtoprogram
—
?
Pointers and dynamic objects/ Slide 51
Memory Leak Problem
int *A = new int [5];
for(int i=0; i<5; i++)
A[i] = i;
A = new int [5];
A 0 1 2 3 4
— — — — —
Theselocationscannotbe
accessedbyprogram
A 0 1 2 3 42
Pointers and dynamic objects/ Slide 52
A Dynamic 2D Array
A dynamic array is
an array of pointers
to save space when
not all rows of the
array are full.
int **table;
32 18 2412
42 141912161113
1811
13 1413
22
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;
table[0]
table[1]
table[2]
table[3]
table[4]
table[5]
table
Pointers and dynamic objects/ Slide 53
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;
Pointers and dynamic objects/ Slide 54
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;
Pointers and dynamic objects/ Slide 55
nt m, n;
in >> m >> n >> endl;
nt** mat;
at = new int*[m];
or (int i=0;i<m;i++)
mat[i] = new int[n];
Create a matrix of any dimensions, m by n:
int m, n;
cin >> m >> n >> endl;
int** mat;
mat = imatrix(m,n);
…
int** imatrix(nr, nc) {
int** m;
m = new int*[nr];
for (int i=0;i<nr;i++)
m[i] = new int[nc];
return m;
}
Put it into a function:

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Pointer in C
Pointer in CPointer in C
Pointer in C
 
Function in c
Function in cFunction in c
Function in c
 
C pointer
C pointerC pointer
C pointer
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Pointers in c++ by minal
Pointers in c++ by minalPointers in c++ by minal
Pointers in c++ by minal
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
This pointer
This pointerThis pointer
This pointer
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Learn C
Learn CLearn C
Learn C
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
File in C language
File in C languageFile in C language
File in C language
 
Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 

Destacado (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
File Pointers
File PointersFile Pointers
File Pointers
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Extending Python with ctypes
Extending Python with ctypesExtending Python with ctypes
Extending Python with ctypes
 
C Types - Extending Python
C Types - Extending PythonC Types - Extending Python
C Types - Extending Python
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Algorithms & flowcharts
Algorithms & flowchartsAlgorithms & flowcharts
Algorithms & flowcharts
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
System's Specification
System's SpecificationSystem's Specification
System's Specification
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Handling computer files
Handling computer filesHandling computer files
Handling computer files
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
14 file handling
14 file handling14 file handling
14 file handling
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 

Similar a Pointers and dynamic memory in C

Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxhappycocoman
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
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 ProcessingMeghaj Mallick
 
Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Abdullah khawar
 
Pointers in Programming
Pointers in ProgrammingPointers in Programming
Pointers in ProgrammingHamadZia1
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxssuser3cbb4c
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th StudyChris Ohk
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 

Similar a Pointers and dynamic memory in C (20)

Pointers
PointersPointers
Pointers
 
Pointer
PointerPointer
Pointer
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptx
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Pointers
PointersPointers
Pointers
 
pointers
pointerspointers
pointers
 
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
 
Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]
 
Pointers in Programming
Pointers in ProgrammingPointers in Programming
Pointers in Programming
 
pointers
pointerspointers
pointers
 
12
1212
12
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Pointers
PointersPointers
Pointers
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 

Más de sanya6900

.Net framework
.Net framework.Net framework
.Net frameworksanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
Type conversions
Type conversionsType conversions
Type conversionssanya6900
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Memory allocation
Memory allocationMemory allocation
Memory allocationsanya6900
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03sanya6900
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)sanya6900
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2sanya6900
 

Más de sanya6900 (12)

.Net framework
.Net framework.Net framework
.Net framework
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
Type conversions
Type conversionsType conversions
Type conversions
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
Ch7
Ch7Ch7
Ch7
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
C cpluplus 2
C cpluplus 2C cpluplus 2
C cpluplus 2
 

Último

Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 

Último (20)

Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 

Pointers and dynamic memory in C

  • 2. Pointers and dynamic objects/ Slide 2 Topics Pointers Memory addresses Declaration Dereferencing a pointer Pointers to pointer Static vs. dynamic objects new and delete
  • 3. Pointers and dynamic objects/ Slide 3 Computer Memory Each variable is assigned a memory slot (the size depends on the data type) and the variable’s data is stored there Variable a’s value, i.e., 100, is stored at memory location 1024 100100…… …… 10241024 …… emory address: 1024 1032 int a = 100; …… 1020 a
  • 4. Pointers and dynamic objects/ Slide 4 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 100100…… …… 10241024 …… Memory address: 1024 1032 …… 1020 integer pointer
  • 5. Pointers and dynamic objects/ Slide 5 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
  • 6. Pointers and dynamic objects/ Slide 6 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
  • 7. Pointers and dynamic objects/ Slide 7 Address Operator & The "address of " operator (&) gives the memory address of the variable Usage: &variable_name 100100…… …… …… …… Memory address: 1024 int a = 100; //get the value, cout << a; //prints 100 //get the memory address cout << &a; //prints 1024 …… 1020 a
  • 8. Pointers and dynamic objects/ Slide 8 Address Operator & 1001008888 …… …… …… Memory address: 1024 1032 a …… 1020 b #include <iostream> using namespace std; void main(){ int a, b; a = 88; b = 100; cout << "The address of a is: " << &a << endl; cout << "The address of b is: " << &b << endl; } Result is: The address of a is: 1020 The address of b is: 1024
  • 9. Pointers and dynamic objects/ Slide 9 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 Variables 1001008888 …… 10241024 …… Memory address: 1024 1032 …… 1020 a p int a = 100; int *p = &a; cout << a << " " << &a <<endl; cout << p << " " << &p <<endl; Result is: 100 1024 1024 1032
  • 10. Pointers and dynamic objects/ Slide 10 Pointer to Pointer What is the output? 58 58 58
  • 11. Pointers and dynamic objects/ Slide 11 Dereferencing Operator * We can access to the value stored in the variable pointed to by using the dereferencing operator (*), 1001008888 …… 10241024 …… Memory address: 1024 1032 …… 1020 int a = 100; int *p = &a; cout << a << endl; cout << &a << endl; cout << p << " " << *p << endl; cout << &p << endl; Result is: 100 1024 1024 100 1032 a p
  • 12. Pointers and dynamic objects/ Slide 12 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 b = *p3; //assign c to b *p2 = *p3; //assign c to a cout << a << b << c; Result is: 888
  • 13. Pointers and dynamic objects/ Slide 13 A Pointer Example The code void doubleIt(int x, int * p) { *p = 2 * x; } int main(int argc, const char * argv[]) { int a = 16; doubleIt(9, &a); return 0; } Box diagram Memory Layout 9x p (8200) x (8196) 16a main doubleIt p a (8192) 16 9 8192 main doubleIt a gets 18
  • 14. Pointers and dynamic objects/ Slide 14 Another Pointer Example #include <iostream> using namespace std; int main (){ 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; } Result is value1==10 / value2==20
  • 15. Pointers and dynamic objects/ Slide 15 Another Pointer Example int a = 3; char s = ‘z’; double d = 1.03; int *pa = &a; char *ps = &s; double *pd = &d; cout << sizeof(pa) << sizeof(*pa) << sizeof(&pa) << endl; cout << sizeof(ps) << sizeof(*ps) << sizeof(&ps) << endl; cout << sizeof(pd) << sizeof(*pd) << sizeof(&pd) << endl;
  • 16. Pointers and dynamic objects/ Slide 16 Reference Variables A reference is an additional name to an existing memory location 9x ref Pointer: 9 x ref Reference: int x=9; int *ref; ref = &x; int x = 9; int &ref = x;
  • 17. Pointers and dynamic objects/ Slide 17 Reference Variables A reference variable serves as an alternative name for an object int m = 10; int &j = m; // j is a reference variable cout << “value of m = “ << m << endl; //print 10 j = 18; cout << “value of m = “ << m << endl; // print 18
  • 18. Pointers and dynamic objects/ Slide 18 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
  • 19. Pointers and dynamic objects/ Slide 19 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; }
  • 20. Pointers and dynamic objects/ Slide 20 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; }
  • 21. Pointers and dynamic objects/ Slide 21 Pointers and Arrays The name of an array points only to the first element not the whole array. 1000 1012 1016 1004 1008
  • 22. Pointers and dynamic objects/ Slide 22 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
  • 23. Pointers and dynamic objects/ Slide 23 Dereferencing An Array Name #include <iostream> using namespace std; void main(){ int a[5] = {2,4,6,8,22}; cout << *a << " " << a[0]; } //main 2 4 8 6 22a[4] a[0] a[2] a[1] a[3] a a This element is called a[0] or *a
  • 24. Pointers and dynamic objects/ Slide 24 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 2 2 #include <iostream> using namespace std; void main(){ int a[5] = {2,4,6,8,22}; int *p = a; cout << a[0] << " " << *p; } 2 4 8 6 22a[4] a[0] a[2] a[1] a[3] a p a
  • 25. Pointers and dynamic objects/ Slide 25 Multiple Array Pointers Both a and p are pointers to the same array. 2 2 4 4 #include <iostream> using namespace std; void main(){ int a[5] = {2,4,6,8,22}; int *p = &a[1]; cout << a[0] << " " << p[-1]; cout << a[1] << " " << p[0]; } 2 4 8 6 22a[4] a[0] a[2] a[1] a[3] p p[0] a[0]
  • 26. Pointers and dynamic objects/ Slide 26 Pointer Arithmetic Given a pointer p, p+n refers to the element that is offset from p by n positions. 2 4 8 6 22 a a + 2 a + 4 a + 3 a + 1 p p + 2 p + 3 p - 1 p + 1
  • 27. Pointers and dynamic objects/ Slide 27 *(a+n) is identical to a[n] Dereferencing Array Pointers 2 4 8 6 22 a a + 2 a + 4 a + 3 a + 1 a[3] or *(a + 3) a[2] or *(a + 2) a[1] or *(a + 1) a[0] or *(a + 0) a[4] or *(a + 4) Note: flexible pointer syntax
  • 28. Pointers and dynamic objects/ Slide 28 Array of Pointers & Pointers to Array a b c An array of Pointers p int a = 1, b = 2, c = 3; int *p[5]; p[0] = &a; p[1] = &b; p[2] = &c; int list[5] = {9, 8, 7, 6, 5}; int *p; P = list;//points to 1st entry P = &list[0];//points to 1st entry P = &list[1];//points to 2nd entry P = list + 1; //points to 2nd entry A pointer to an array
  • 29. Pointers and dynamic objects/ Slide 29 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!
  • 30. Pointers and dynamic objects/ Slide 30 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]; }
  • 31. Pointers and dynamic objects/ Slide 31 Pointer to 2-Dimensional Arrays table[ 0] or *( table + 0 ) table table[ 1] or *( table + 1 ) table + 1 table[ 2] or *( table + 2 ) table + 2 int table[3][4] = {{1,2,3,4}, {5,6,7,8},{9,10,11,12}}; for(int i=0; i<3; i++){ for(int j=0; j<4; j++) cout << *(*(table+i)+j); cout << endl; } *(table[i]+j) = table[i][j]What is **table ? table[i] = &table[i][0] refers to the address of the ith row
  • 33. Pointers and dynamic objects/ Slide 33 Memory Management Static Memory Allocation Memory is allocated at compilation time Dynamic Memory Memory is allocated at running time
  • 34. Pointers and dynamic objects/ Slide 34 Static vs. Dynamic Objects Static object (variables as declared in function calls) Memory is acquired automatically Memory is returned automatically when object goes out of scope Dynamic object Memory is acquired by program with an allocation request  new operation Dynamic objects can exist beyond the function in which they were allocated Object memory is returned by a deallocation request  delete operation
  • 35. Pointers and dynamic objects/ Slide 35 Memory Allocation { int a[200]; … } int* ptr; ptr = new int[200]; … delete [] ptr; new delete
  • 36. Pointers and dynamic objects/ Slide 36 Object (variable) creation: New Syntax ptr = new SomeType; where ptr is a pointer of type SomeType p Uninitialized int variable Example int* p = new int;
  • 37. Pointers and dynamic objects/ Slide 37 Object (variable) destruction: Delete Syntax delete p; storage pointed to by p is returned to free store and p is now undefined p Example int* p = new int; *p = 10; delete p; 10
  • 38. Pointers and dynamic objects/ Slide 38 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
  • 39. Pointers and dynamic objects/ Slide 39 Example Dynamic Memory Allocation Request for “unnamed” memory from the Operating System int *p, n=10; p = new int; p = new int[100]; p new p new p = new int[n]; p new
  • 40. Pointers and dynamic objects/ Slide 40 Memory Allocation Example Want an array of unknown size main() { 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 . . . }
  • 41. Pointers and dynamic objects/ Slide 41 Freeing (or deleting) Memory
  • 42. Pointers and dynamic objects/ Slide 42 A Simple Dynamic List Example cout << "Enter list size: "; int n; cin >> n; int *A = new int[n]; if(n<=0){ cout << "bad size" << endl; return 0; } initialize(A, n, 0); // initialize the array A with value 0 print(A, n); A = addElement(A,n,5); //add an element of value 5 at the end of A print(A, n); A = deleteFirst(A,n); // delete the first element from A print(A, n); selectionSort(A, n); // sort the array (not shown) print(A, n); delete [] A;
  • 43. Pointers and dynamic objects/ Slide 43 Initialize void initialize(int list[], int size, int value){ for(int i=0; i<size; i++) list[i] = value; }
  • 44. Pointers and dynamic objects/ Slide 44 print() void print(int list[], int size) { cout << "[ "; for(int i=0; i<size; i++) cout << list[i] << " "; cout << "]" << endl; }
  • 45. Pointers and dynamic objects/ Slide 45 Adding Elements // for adding a new element to end of array int* addElement(int list[], int& size, int value){ int* newList = new int [size+1]; // make new array if(newList==0){ cout << "Memory allocation error for addElement!" << endl; exit(-1); } for(int i=0; i<size; i++) newList[i] = list[i]; if(size) delete [] list; newList[size] = value; size++; return newList; }
  • 46. Pointers and dynamic objects/ Slide 46 Delete the first element // for deleting the first element of the array int* deleteFirst(int list[], int& size){ if(size <= 1){ if( size) delete list; size = 0; return NULL; } int* newList = new int [size-1]; // make new array if(newList==0){ cout << "Memory allocation error for deleteFirst!" << endl; exit(-1); } for(int i=0; i<size-1; i++) // copy and delete old array newList[i] = list[i+1]; delete [] list; size--; return newList; }
  • 47. Pointers and dynamic objects/ Slide 47 Adding Element (version 2) // for adding a new element to end of array void addElement( int * & list, int & size, const int value ){ int * newList = new int [size + 1]; if( newList == NULL ){ cout << "Memory allocation error for addElement!" << endl; exit(-1); } for( int i = 0; i < size; i++ ) newList[ i ] = list[ i ]; if( size ) delete [] list; newList[ size ] = value; size++; list = newList; return; }
  • 48. Pointers and dynamic objects/ Slide 48 Deleting Element (version 2) void deleteFirst( int * & list, int & size ){ if( size <= 1 ){ if( size ) delete list; list = NULL; size = 0; return; } delete list; // delete the first element list++; size--; return; }
  • 49. Pointers and dynamic objects/ Slide 49 Another Main program int main(){ int * A = NULL; int size = 0; int i; for( i = 0; i < 10; i++ ) addElement( A, size, i ); for( i = 0; i < 10; i++ ) cout << A[i] << " "; cout << endl; for( i = 0; i < 4; i++ ) deleteFirst( A, size ); for( i = 0; i < 6; i++ ) cout << A[i] << " "; cout << endl; return 0; } 0 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9
  • 50. Pointers and dynamic objects/ Slide 50 Dangling Pointer Problem int *A = new int[5]; for(int i=0; i<5; i++) A[i] = i; int *B = A; delete [] A; B[0] = 1; // illegal! A B 0 1 2 3 4 A B Locationsdonotbelongtoprogram — ?
  • 51. Pointers and dynamic objects/ Slide 51 Memory Leak Problem int *A = new int [5]; for(int i=0; i<5; i++) A[i] = i; A = new int [5]; A 0 1 2 3 4 — — — — — Theselocationscannotbe accessedbyprogram A 0 1 2 3 42
  • 52. Pointers and dynamic objects/ Slide 52 A Dynamic 2D Array A dynamic array is an array of pointers to save space when not all rows of the array are full. int **table; 32 18 2412 42 141912161113 1811 13 1413 22 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; table[0] table[1] table[2] table[3] table[4] table[5] table
  • 53. Pointers and dynamic objects/ Slide 53 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;
  • 54. Pointers and dynamic objects/ Slide 54 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;
  • 55. Pointers and dynamic objects/ Slide 55 nt m, n; in >> m >> n >> endl; nt** mat; at = new int*[m]; or (int i=0;i<m;i++) mat[i] = new int[n]; Create a matrix of any dimensions, m by n: int m, n; cin >> m >> n >> endl; int** mat; mat = imatrix(m,n); … int** imatrix(nr, nc) { int** m; m = new int*[nr]; for (int i=0;i<nr;i++) m[i] = new int[nc]; return m; } Put it into a function:

Notas del editor

  1. &amp;lt;number&amp;gt; Note the signature of main() – it’s an array parameter. And, like other examples we’ve given, it takes the number of elements as a parameter. Why?
  2. &amp;lt;number&amp;gt; References fix some of those pointer problems. If we wanted something called “ref” to point to a variable x, we’d declare a pointer variable and assign the address of x into it. With references, we’d attach an additional name – ref – to the same memory location as x. Note how the pointer necessitates an extra variable, whereas the reference didn’t