Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Reference Types
• Review on Pointers
• Reference Variables
• Dynamic Memory Allocation
– The new operator
– The delete operator
– Dynamic Memory Allocation for Arrays
1
C++ Data Types
simple structured
pointer reference
2
Recall that . . .
char str [ 8 ];
6000
3
Addresses in Memory
• When a variable is declared, enough memory to hold a value
of that type is allocated for it at an unused memory location.
This is the address of the variable
int x;
float number;
char ch;
x number ch
4
Obtaining Memory Addresses
• The address of a non-array variable can be obtained by using
the address-of operator &
2000 2002 2006
int x;
float number;
x number ch
char ch;
5
What is a pointer variable?
6
Using a Pointer Variable
2000
int x;
12
x = 12;
x
3000
int* ptr;
2000
ptr = &x;
ptr
3000
int* ptr;
2000
ptr = &x;
ptr
cout << *ptr;
3000
int* ptr;
2000
ptr = &x;
ptr
*ptr = 5;
// changes the value at the
address ptr points to 5
9
Self –Test on Pointers
4000
char ch;
A Z
ch = ‘A’;
ch
ptr
11
Reference Variables
Reference variable = alias for another variable
- Contains the address of a variable (like a pointer)
- No need to perform any dereferencing (unlike a pointer)
- Must be initialized when it is declared
int x = 5;
int &z = x; // z is another name for x
int &y ; //Error: reference must be initialized
cout << x << endl; -> prints 5
cout << z << endl; -> prints 5
z = 9; // same as x = 9;
13
Reference Variables Example
#include <iostream.h>
void p_swap(int *a, int *b)
{
// Function prototypes
(required in C++) int temp;
temp = *a; (2)
void p_swap(int *, int *); *a = *b; (3)
*b = temp;
void r_swap(int&, int&);
}
int main (void){
void r_swap(int &a, int &b)
int v = 5, x = 10;
{
cout << v << x << endl;
int temp;
p_swap(&v,&x);
temp = a; (2)
cout << v << x << endl;
a = b; (3)
r_swap(v,x); b = temp;
cout << v << x << endl; }
return 0;
14
}
Dynamic Memory Allocation
In C and C++, three types of memory are used by programs:
15
3 Kinds of Program Data
• STATIC DATA: Allocated at compiler time
Run-time allocated
Stack
memory
Heap
Compile-time
static data
allocated
memory
Program
code
Low-end
17
Dynamic Memory Allocation
• In C, functions such as malloc() are used to
dynamically allocate memory from the Heap.
• In C++, this is accomplished using the new and
delete operators
• new is used to allocate memory during execution time
– returns a pointer to the address where the object is
to be stored
– always returns a pointer to the type that follows the
new
18
Operator new Syntax
new DataType
ptr
ptr = new char;
5000
*ptr = ‘B’; ‘B’
delete Pointer
delete [ ] Pointer
ptr
ptr = new char;
5000
*ptr = ‘B’; ‘B’
NOTE:
cout << *ptr; delete deallocates the
memory pointed to by ptr
delete ptr;
23
Example
char *ptr ;
3000
ptr
ptr = new char[ 5 ]; ???
NULL
6000
???
24
Pointers and Constants
char* p;
p = new char[20];