Professional Documents
Culture Documents
1
Representation of Data
All data in a the computer’s memory is represented as a sequence of bits:
Bit : unit of storage, represents the level of an electrical charge. Can be either 0 or 1.
0 1
Byte (a.k.a Octet): 8 bits make up a byte, and a character is one byte
A byte can represent 256 (0…255) different symbols:
27 26 25 24 23 22 21 20
0 0 0 0 0 0 0 0 0 //binary representation and corresponding integer values
0 0 0 0 0 0 0 1 1
0 0 0 0 0 0 1 0 2
0 0 0 0 0 0 1 1 3
...
1 0 0 0 0 0 0 0 128
1 0 0 0 0 0 0 1 129
...
1 1 1 1 1 1 1 0 254
1 1 1 1 1 1 1 1 255
0 0 1 0 | 0 1 0 0 | _ _ _ _ | _ _ _ _| _ _ _ _ | _ _ _ _ | _ _ _ _ | _ _ _ _
3
Hex Numbers: ctd.
0x2435AF00 + 1 = 0x2435AF01
0x2435AEFF + 1 = 0x2435AF00
4
Memory
What happens when we define variables:
char c = 'A';
int n = 5; c 0x2435af00
Code of 'A' n
0x2435af01
0x2435af00
.
01000001 c .
.
0x2435af01 00000000 n
00000000
00000000 Symbol table: variables and
00000101 5 in binary their memory addresses are
... listed here; Symbol table is
not something that you can
directly manipulate in
program
Memory: variables are stored here
5
Pointers
A pointer is a variable to store an “address in computer memory”
Thus it points to a memory location
A pointer is something you can 01000001 c
manipulate in program
00000101 n
char c = 'A';
char * p;
p = &c;
...
0x2435af00 p
Memory
Purpose:
– Basis for implementing linked data structures linked lists, trees, graphs...
6
– Provide dynamic memory allocation, variable-size arrays
Overview
There are a couple of things you can do with pointers:
– Declare one: int * ptr;
char * pchar;
Date * pdate
7
Pointers: definition
A pointer is defined as: type * pointer_variable;
e.g. char * ptr;
pointer_variable does not store a type value, but stores the address of a
memory location that stores a type value
c A
char c = 'A';
char *p; what happens in memory p ?
char *q = NULL
q
You can never know to where an unititialized pointer points (i.e. the address of the
memory location that it keeps)
NULL is defined in standard header files to mean “nowhere” or ”nothing”. It can be
used as the initial value for a variable that does not point to anywhere. Normally this
value is 0 and it can also be used as nullptr 8
Pointers: “address of” operator (&)
You can store the address of variable in a pointer variable:
Actually stores
the code of 'A'
char c = 'A'; c A
char * p; .
.
p = &c; what happens in memory .
p 0x2435af00
Be careful about the types; the type of variable used with & must be the
same as the one of the pointer’s type used with * (e.g. address of a char
variable can be assigned to a char pointer, address of int var. to int
pointer, etc.).
Assigning an existing variable’s address is not the main use of pointers; but,
this is useful in explaining the concept of address storage.
9
Pointers: dereferencing
*pointer-variable
derefence (or indirection) operator. It gives the content of
memory location pointed by the pointer-variable
char c = 'A';
char * p; c A
p = &c; .
.
what happens in memory .
p 0x2435af00
cout << *p;
just like “cout << c;” prints the value of the char variable
A
10
Pointers: assignment
17.5
p n
Now you can assign p to another pointer variable:
double *q;
q = p; // q and p points to the same location in memory
q
n
p 17.5 11
Pointers: definition
(what happens behind the scenes)
char c = 'A';
char *p; c 0x2435af00
p 0x2435af01
0x2435af00
.
A c .
0x2435af01 ? p .
. Symbol table
.
.
//a pointer uses 4 bytes of memory
when you have 32-bit adresses
Memory
12
Pointers: address of a variable
(what happens behind the scenes)
c 0x2435af00
char c = 'A';
p 0x2435af01
char *p;
p = &c; // p now points to c. .
.
.
.
c A
.
.
p
13
Memory
Pointers: dereferencing
(what happens behind the scenes)
char c = 'A';
char *p;
p = &c; // p now points to c. c 0x2435af00 //unchanged
*p = 'B'; p 0x2435af01
.
.
.
0x2435af00 A B
0x2435af01 0x2435af00 Symbol table
.
c A B
.
p
Memory 14
Some Remarks
What happens if you try to assign a string/int/double expression to a
pointer variable?
– e.g. double *q;
q = 123.45;
:syntax error
Example
double *p; //a pointer for double type, but currently points nowhere
p ?
p = new double; // memory is allocated to store a double value, but
//currently not initialized. p now points to that location
p ?
16
Pointers and Dynamic Allocation for user-
defined types/classes
You can have pointers for any type:
– built-in or user-defined types, classes and structs
– e.g. int, double, char, string, robot, dice, date, …
You can dynamically allocate memory for any type; note that
the class constructor is called automatically to construct the
object:
myClass * classPtr;
classPtr = new myClass;
17
Pointer to Class Members
3
int month = (*p1).Month(); //month
9
int day = p1->Day(); //day
ptr-> is a shorthand for (*ptr). if ptr is a pointer to a struct or a class 18
Dynamic memory allocation with new –
Allocating Multiple Variables
int *p1, *p2;
new keyword dynamically allocates enough memory for a single int, and
returns its address, which is stored in p1
p1 = new int;
In general, the new keyword dynamically allocates enough memory for the
following type and count. Pointer p2 points to the first element of the list.
This is how we generate DYNAMIC ARRAYs.
p2 = new int[4];
type count
19
p2
Allocation of multiple variables with new
Assume that we want to hold a dynamic array to hold
vacation dates of varying numbers:
20
Allocation of multiple variables with new
Similarly, we can have a pointer to a list of 100 integers:
21
Manipulation using pointers
You can also manipulate such an array
using pointer syntax.
23
Linked Lists
Built-in Arrays: - too much or too little memory may be allocated
+ ease of use
- inserting an element into a sorted array may require shifting
all the elements
- deleting an element requires shifting
24
Linked Lists
head
25
Introduction to linked lists: definition
Consider the following struct definition
p ? ? ?
26
Reminder: structs: as data aggregates
see Tapestry Chp. 7 pp. 330-
If you need to create a data structure in order to combine different attributes of a
concept, you can struct. These attributes are also called as "tied" data. For
example, you can create a struct for a student and store a student's id, grade,
address in this struct. Another example follows:
Very similar to classes - but no member functions. You should use structs rather than classes
only when you want to use them as data aggregates, without any member function (you may
have a constructor though, see the next slide).
Well, it is possible to have member functions for structs, but we will not use structs like that.
27
Structs with constructors
If you define one or more constructors:
struct point Instead of:
{
double x;
double y; point curve[100];
General Remarks:
If no constructor is used, it is OK.
If you want to have a constructor with parameter, also write a default constructor.
If there is constructor, creating a struct (dynamic or normal) variable automatically 28
calls default constructor (e.g. curve has 100 elements, all are (0,0) when created)
Introduction to linked lists: inserting a node
Without a constructor: With a constructor:
5 Ali
p
num word next
29
Updated node struct with constructor
In order to use the struct as in the previous slide, we need to add a
constructor to it:
node *p;
p = new node(5,"Ali",NULL);
node *q;
q
?
5 Ali
p
num word next
31
Introduction to linked lists
node *p;
p = new node;
p = new node(5,"Ali",NULL);
node *q;
q = new node;
5 Ali ? ? ? ?
p
num word next num word next
32
Introduction to linked lists
node *p, *q;
p = new node;
p = new node(5,"Ali",NULL);
q = new node;
q->num=8; //I can access fields one by one
q->word = "Veli";
q->next = NULL;
q
5 Ali ? 8 Veli
p
num word next num word next
33
Introduction to linked lists
node *p, *q;
p = new node;
p = new node(5,"Ali",NULL);
q = new node(8,"Veli",NULL);
//or I can use constructor
p->next = q;
5 Ali ? 8 Veli
p
num word next num word next
34
Linked Lists: Typical Functions
head
head
39
Static vs. Dynamic Memory Allocation
Automatic (ordinary) variables: Normal declaration of variables within a function (including
main): e.g. ints, chars that you define by “int n;” , “char c;” etc..
– C++ allocates memory on the stack (a pool of memory cells) for automatic
variables when a function begins, releases the space when the function completes
(automatically).
– The lifetime of an automatic variable is defined by its scope (the compound block
in which the variable is defined). After the block finishes, the variable’s location is
returned to memory.
• A block is defined as any code fragment enclosed in an left curly brace, {, and
a right curly brace, }.
Dynamic variables: Allocated by the new operator, on the heap (a storage pool of
available memory cells for dynamic allocation). E.g. p = new int[100];
– new returns the address of the first element allocated (this is generally assigned to
a pointer variable)
– System will return NULL if there is no more space in heap to be allocated.
– Programmer should use delete to release space when it is no longer needed.
• If you do not do so, you cause so-called "memory leak"; This is one of
deadly sins of programming.
– The lifetime of a dynamic variable is until they are explicitly deleted
40
Local Variables vs Global Variables
• A block is any code fragment enclosed in an left curly brace, {,
and a right curly brace, }.
Heap
• The heap is basically rest of memory that the program has. In that sense, it is
often the largest segment in a program.
• Dynamic variables are allocated on the heap and memory allocated for them
stays until explicitly freed (deleted).
• The memory area used for static and global variable allocation is basically part of
heap, but mostly the area used for dynamically allocated variables is separated
from static/global See stackheapaddress.cpp
– This is compiler dependant 44
Heap/Stack
45
Pointers: Delete
The statement to de-allocate a memory location and return to
the heap is:
delete PointerVariable;
– the memory location pointed by PointerVariable is now returned
back to the heap;
– this area now may be reallocated with a new statement
...
int num;
int *ptr;
num=5;
ptr = # //ptr contains the address of num;
cout << *ptr << endl;
What is output?
48
Question
int n;
int * p_temp = &n;
49
Memory allocation with the new operator
Points to be careful for
Warning message: address of local variable returned
What is the problem here?
Dice * MakeDie(int n)
//return pointer to n sided object
{
Dice nSided(n);
return &nSided;
}
Solution:
Dice * MakeDie(int n)
//return pointer to n sided object
{
Dice * dice_ptr = new Dice (n); dice_ptr
return dice_ptr;
}
Dice * cube = MakeDie (4); cube
Dice * tetra = MakeDie (6);
cout << cube->NumSides();
//Is there any problem left?
52