Pointers and Dynamic Memory
Nguyen Le Hoang Dung
nlhdung@[Link]
Contents
n Pointers and Dynamic Memory
q What are pointers
q Why dynamically allocate memory
q How to dynamically allocate memory
q What about deallocation?
q Walk through pointer exercises
n Programming Assignment Discussion
q Stage #2
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 2
Pointers
n In C++, a pointer is just a different kind of
variable.
n This type of variable points to another variable or
object
q (i.e., it is used to store the memory address of another
variable nor an object).
q Such pointers must first be defined and then
initialized.
q Then, they can be manipulated.
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 3
Pointers
n A pointer variable is simply a new type of
variable.
q Instead of holding an int, float, char, or some
object's data....it holds an address.
q A pointer variable is assigned memory.
q The contents of the memory location is some
address of another “variable”.
q Therefore, the value of a pointer is a memory
location.
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 4
Pointers
n We can have pointers to (one or more)
q integers
q floating point types
q characters
q structures
q objects of a class
n Each represents a different type of pointer
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 5
Pointers
n We define a pointer to an integer by:
int * ptr; //same as int *ptr;
n Read this variable definition from right to
left:
q ptr is a pointer (that is what the * means) to an
integer.
q this means ptr can contain the address of
some other integer
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 6
Pointers
n At this point, you may be wondering why
pointers are necessary.
n They are essential for allowing us to use
data structures that grow and shrink as the
program is running.
q after midterm time we will learn how to do
this...with linked lists
n We are no longer stuck with a fixed size array
throughout the lifetime of our program.
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 7
Pointers
n But first,
q we will learn that pointers can be used to allow
us to set the size of an array at run-time
versus fixing it at compilation time;
q if an object is a list of names...then the size of
that list can be determined dynamically while
the program is running.
q This cannot be accomplished in a user-friendly
way with simple arrays!
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 8
Defining Pointers
n So, what are the data types for the
following variables?
int *ptr1, obj1; //watch out!
char *ptr2, *ptr3;
float obj2, *ptr4;
n What are their initial values (if local
variables)? -- yes, garbage --
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 9
Defining Pointers
n The best initial value for a pointer is
q zero (address zero),
q also known as NULL (this is a #define
constant in the iostream library for the value
zero!)
q The following accomplish the same thing:
int *ptr1 = NULL;
int *ptr2 = 0;
int *ptr3 (0);
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 10
Defining Pointers
n You can also initialize or assign the
address of some other variable to a
pointer,
q using the address-of operator
int variable;
int *ptr1 = &variable;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 11
Allocating Memory
n Now the interesting stuff!
n You can allocate memory dynamically (as
our programs are running)
q and assign the address of this memory to a
pointer variable.
int *ptr1 = new int;
?
ptr1
dynamic variable
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 12
int *ptr1 = new int;
n The diagram used is called a
q pointer diagram
q it helps to visualize what memory we have
allocated and what our pointers are
referencing
q notice that the dynamic memory allocated is of
size int in this case
q and, its contents is uninitialized
q new is an operator and supplies back an
address of the memory set allocated
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 13
Dereferencing
n Ok, so we have learned how to set up a
pointer variable to point to another variable
or to point to memory dynamically
allocated.
n But, how do we access that memory to set
or use its value?
n By dereferencing our pointer variable:
*ptr1 = 10;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 14
Dereferencing
n Now a complete sequence:
int *ptr1;
ptr1 = new int;
*ptr1 = 10;
•••
cout <<*ptr1; //displays 10
10
ptr1
dynamic variable
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 15
Deallocating
n Once done with dynamic memory,
q we must deallocate it
q C++ does not require systems to do “garbage
collection” at the end of a program’s
execution!
n We can do this using the delete operator:
delete ptr1;
this does not delete the pointer variable!
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 16
Deallocating
n Again:
this does not delete the pointer variable!
n Instead, it deallocates the memory
referenced by this pointer variable
q It is a no-op if the pointer variable is NULL
q It does not reset the pointer variable
q It does not change the contents of memory
q Let’s talk about the ramifications of this...
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 17
Pointer usage
n Passing pointer to
function:
void myFunction(int *p){
q Pass-by-value *p = *p + 1;
n Pass copy of pointer to p = p + 1;
function. }
int main() {
n Address stored in pointer is int x = 5;
NOT CHANGED. int *pointer = &x;
n Variable that pointer points to
myFunction(pointer);
CAN BE CHANGED.
return 0;
}
//'x' is changed but 'pointer'
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 18
Pointer usage
n Passing pointer to
function:
void myFunction(int* &p){
q Pass-by-reference *p = *p + 1;
n Pass real pointer to function. p = p + 1;
}
n Address stored in pointer int main() {
CAN BE CHANGED. int x = 5;
n Variable that pointer points to int *pointer = &x;
CAN BE CHANGED.
myFunction(pointer);
return 0;
}
//'x’ & 'pointer' are changed
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 19
Demo
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 20
Allocating Arrays
n But, you may be wondering:
q Why allocate an integer at run time
(dynamically) rather than at compile time
(statically)?
n The answer is that we have now learned
the mechanics of how to allocate memory
for a single integer.
n Now, let’s apply this to arrays!
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 21
Allocating Arrays
n By allocating arrays dynamically,
q we can wait until run time to determine what
size the array should be
q the array is still “fixed size”...but at least we
can wait until run time to fix that size
q this means the size of a dynamically allocated
array can be a variable!!
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 22
Allocating Arrays
n First, let’s remember what an array is:
q the name of an array is a constant address
to the first element in the array
q So, saying char name[21];
means that name is a constant pointer who’s
value is the address of the first character in a
sequence of 21 characters
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 23
Allocating Arrays
n To dynamically allocate an array
q we must define a pointer variable to contain an
address of the element type
n For an array of characters we need a pointer to
a char:
char *char_ptr;
n For an array of integers we need a pointer to an
int:
int *int_ptr;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 24
Allocating Arrays
n Next, we can allocate memory and
examine the pointer diagram:
int size = 21; //for example
char *char_ptr;
char_ptr = new char [size];
char_ptr
21 characters
(elements 0-20)
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 25
Allocating Arrays
n Some interest thoughts:
q the pointer diagram is identical to the pointer
diagram for the statically allocated array
discussed earlier!
q therefore, we can access the elements in the
exact same way we do for any array:
char_ptr[index] = ‘a’; //or
[Link](char_ptr,21,’\n’);
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 26
Allocating Arrays
n The only difference is when we are finally
done with the array,
q we must deallocate the memory:
delete [] char_ptr;
not-your-memory
char_ptr
It is best, after doing this to say: char_ptr = NULL;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 27
Allocating Arrays
n One of the common errors we get
q once allocating memory dynamically
q is a segmentation fault
q it means you have accessed memory that is
not yours,
n you have dereferenced the null pointer,
n you have stepped outside the array bounds,
n or you are accessing memory that has already been
deallocated
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 28
Pointer vs Array – Pointer to array
int array[3], *parray;
parray = array; // Cách 1
parray = &array[0]; // Cách 2
18 19 1A 1B 1C 1D 1E 1F
… 0B 00 00 00 …
parray
0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17
… …
array
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 29
Pointer vs Array
n Pointer increment/decrement:
q Stored address inc/dec follows pointer type.
q Formula:
n <Pointer> +/- k = <Address> +/- k * sizeof(<Pointer
Type>).
int a[10] = {1,2,3};
int *p = a;
cout << *(p+1) << endl;
cout << *(p+2) << endl;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 30
Pointer vs Array
p = array
+2
+1
0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17
… …
int array[3];
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 31
Pointer vs Array
n Another way for accessing memory
content pointer points to.
n Usage:
*(<Pointer> + <Index>) ~ <Pointer>[ <Index>]
int a[10] = {1,2,3};
int *p = a;
a[2] = 12; cout << a[2] << endl;
*(p+2) = 22; cout << a[2] << endl;
p[2] = 32; cout << a[2] << endl;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 32
In Review
n On the board, let’s walk through examples
of the following:
q allocating an array of integers dynamically
q deallocating that array
q writing a loop to set the values
q now, allocate an array of video-structures
dynamically
q Show how you’d access the 3rd title
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 33
In Review: Pointer Arithmetic
n When we use the subscript operator,
q pointer arithmetic is really happening
q this means the following are equivalent:
ptr1[3] == *(ptr1+3)
q This means the subscript operator adds the
value of the index to the starting address and
then dereferences the quantity!!!
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 34
Practice 1
n With the following code segment
float pay;
float *ptr_pay;
pay=2313.54;
ptr_pay = &pay;
è Determine the output for
a. pay
b. *ptr_pay
c. *pay
d. &pay
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 35
Practice 2
n Find the error(s) in the following code
int *x, y = 2;
*x = y;
*x += y++;
cout << *x << endl;
cout << y << endl;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 36
Practice 3
n With the following code segment
int *pint;
float f;
char c;
double *pd;
è Determine the invalid syntax:
a. f = *pint;
b. c = *pd;
c. *pint = *pd;
d. pd = f;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 37
Practice 4
n Given the following code:
q Fix error of the code.
q After fixing, what is displayed on screen?
int *x, y = 2;
float *z = &y;
*x = *z + y;
cout << y;
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 38
Practice 5
n Explain the difference amongst the
following 3 functions:
void swap1(int x, int y) { void swap3(int *x, int *y) {
int temp = x; x = y; int temp = *x; *x = *y;
y = temp; *y = temp;
} }
void swap2(int &x, int &y) {
int temp = x; x = y;
y = temp;
}
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 39
Practice 6
n Determine how many bytes between p1
and p2 in the following program:
int main(int argc, const char * argv[]) {
double m[100];
double *p1, *p2;
p1 = m;
p2 = &m[6];
return 0;
}
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 40
Practice 7
n Use pointer to write a program that can
do the following functions:
q Input/Output an array.
q Find a specific element in an array.
q Find the sum of elements that meet specific
requirements
q Count the total number of elements that meet
specific requirements
q Sort the array in ascending/descending order
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 41
Practice 8 (*)
n Using pointer to write a program that can
do the following functions:
q Read from keyboard an array of N fractions.
q Extract negative fractions to another array.
q Display the result on screen.
q Find the sum of positive fractions and display
that result on screen
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 42
For Next Time
n Next time we will discuss:
q more about pointers
q Dynamically allocated memory
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 43
References
n Kỹ thuật lập trình, Khoa CNTT, ĐHKHTN
n C++ Primer Plus, Stephen Prata, SAMS
n C++ Programming: An Object-Oriented Approach, 1st Edition,
Behrouz A. Forouzan, Richard Gilberg, Hill Education, 2019
n Adam Drozdek, Data Structures and Algorithms in C++, 4th
Edition, Cengage Learning, 2008
n Introduction to C++ Programming Concepts and Applications,
John Keyser, Texas A&M University, 2019
n Nguyen Minh Huy, Programming Techniques and Practices
slides, HCMUS
n Dang Binh Phuong, Programming Techniques and Practices
slides, HCMUS
Programming Techniques and Practices – Nguyen Le Hoang Dung 19-Mar-21 44