0% found this document useful (0 votes)
2 views

2023_Slot04_DynamicStructure

Uploaded by

ltmthu07072005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

2023_Slot04_DynamicStructure

Uploaded by

ltmthu07072005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

University of Science – VNU-HCM

Faculty of Information Technology


CSC10002 – Programming Techniques

Session 04 -
Dynamic Structures
Instructor:
Dr. LE Thanh Tung

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 1


Content

1 Dynamic Structures
2 Array of Pointer (Pointer to Pointer – Double Pointer)
3 Pointer to Functions

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 2


Dynamic Structures

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 3


Review
▪ Pointer variable holds memory address
▪ Reference operator: & → to extract address of variable
▪ Dereference operator: * → value of corresponding address

int var = 10; // An integer variable


int* ptr; // Declaration of pointer to int
ptr = &var; // Store the address of var in ptr

cout << "Value of var: " << var << endl;


cout << "Address of var: " << &var << endl;
cout << "Value of ptr (Address of var): " << ptr << endl;
// Dereferencing ptr
cout << "Value pointed to by ptr: " << *ptr << endl;
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 4
Pointers and Arrays

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 5


Dynamic Structures
▪ Think about a pointer of a struct
▪ Consider the struct named Student:
struct Student {
char name[20];
int age;
double gpa;
};
Student* pStudent = new Student;

▪ Then, how would we access the name ?


*pStudent.name ???

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 6


Dynamic Structures
▪ To access a member of a struct, we need to realize that there is a
“precedence” problem
▪ The member access operator (.) have the higher operator precedence
than the dereference operator (*)
▪ So, parens are required:
▪ (*pStudent).name
▪ → so ugly
▪ Alternatively, utilizing indirect member access operator (->)
▪ pStudent->name

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 7


Dynamic Structures
struct Student { int main(){
char name[20]; Student* pStudent = new Student;
int age; cout << "Input student info: ";
double gpa; cin.getline(pStudent->name, 20);
void printStudent(){ cin >> pStudent->age;
cout << name << " - "; cin >> pStudent->gpa;
cout << age << " - ";
cout << gpa << endl; pStudent->printStudent();
}
}; delete pStudent;
return 0;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 8


Dynamic Structures
▪ One of the advantages of using pointers with structs is dynamic memory
allocation
▪ Now, to allocate an array of structures dynamically:
▪ Student* pClass = new Student[10];
▪ In this case, how to access the first student’s name
▪ Now, consider whether pClass[0] is a pointer or not ?
▪ So, we should access via: pClass[0].name
▪ In summary, as using (->) operator, the first operand expects a pointer

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 9


Pointer in Functions
▪ How about passing pointers to functions?
▪ What is the difference between “Pass by value” and “Pass by
reference”
▪ Pass by value: makes a copy of the pointer variable (i.e., a copy of
the address) → Allows functions to modify the data at the memory
address the pointer points to, but not the memory address in the
pointer itself.
▪ Pass by reference: places an address of the pointer variable on the
program stack → Enables functions to modify both the data at the
memory address and the memory address the original pointer holds

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 10


Pointers and Functions

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 11


Pointer in Functions
▪ Passing a pointer by value:
void printStudent(Student* p){
cout << p->name << " - ";
cout << p->age << " - " << p->gpa << endl;
}
Student* pStudent = new Student;
printStudent(pStudent);

▪ pStudent is a pointer to a student object, passed by value.


▪ So, p is a local variable with an initial value of the address of a pStudent
object
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 12
Pointer in Functions
▪ Pass by Reference with Pointers
▪ involves passing the address of the pointer variable itself to the
function
▪ it means you're passing a reference to the pointer, allowing the
function to directly modify the original pointer's value (the address it
holds).
▪ is less common with pointers but can be used for:
▪ allocating memory
▪ reallocating memory
▪ updating the original pointer
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 13
Pointer in Functions
▪ Pass by Reference with Pointers The order of the * and &
is critical!
void createStudent(Student* & p){
p = new Student;
cin.getline(p->name, 20);
cin >> p->age >> p->gpa;
}
Student* pStudent;
createStudent(pStudent);
printStudent(pStudent);

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 14


Pointer in Structure
▪ Think about the attribute “name”
▪ Is it ok to change it into dynamic allocation
▪ So, let’s consider the new structure of Student:
struct Student {
char* name;
int age;
double gpa;
};

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 15


Pointer in Structure
▪ Now, rewrite the createStudent() function to get the new student

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 16


Pointer in Structure
▪ Now, rewrite the createStudent() function to get the new student
void createStudent(Student*& p){
char tmp[20]; Why do we need
cin.get(tmp, 20, '\n’); + 1
p = new Student; here?
p->name = new char[strlen(tmp) + 1];
strcpy(p->name, tmp);
cin >> p->age >> p->gpa;
}
Student* pStudent;
createStudent(pStudent);
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 17
Pointer in Structure
▪ Think about how to delete a pStudent
▪ Now write a function: void deleteStudent(Student*& p)

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 18


Pointer in Structure
▪ Think about how to delete a pStudent
▪ Now write a function: void deleteStudent(Student*& p)

void deleteStudent(Student*& p){


delete[] p->name;
delete p;
p = nullptr;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 19


Array of Pointer

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 20


Array of Pointer
▪ An array of pointers is essentially an array where each element is a
pointer

int var1 = 10, var2 = 20, var3 = 30;


int* arr[3]; // Array of integer pointers

// Assigning addresses to array elements


arr[0] = &var1;
arr[1] = &var2;
arr[2] = &var3;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 21


Pointer to Pointer (Double Pointer)
▪ What is the difference between arr and pptr?
int* arr[10];
int** pptr;
▪ arr is an array of 10 pointers to integers. Each element is a static
pointer and can be dynamically allocated
▪ pptr is a double pointer that points to another pointer variable
▪ We have only 1 static pointer that points to another pointer variable
▪ But we can use this pointer (pptr) to dynamically allocate memory
for the integer pointer that it points to (or even allocate an array of
pointer dynamically)
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 22
Array of Pointer
int* arr[3]; // Array of integer pointers
// Allocate the dynamic memory for each pointer
arr[0] = new int;
arr[1] = new int[2];
arr[2] = new int[4];

arr[0] arr[1] arr[2]

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 23


Array of Pointer
▪ 1. assign 8 into
▪ *arr[0] = 8;
▪ Another way: ???

arr[0] arr[1] arr[2]

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 24


Array of Pointer
▪ 1. assign 8 into
▪ *arr[0] = 8;
▪ arr[0][0] = 8; (Explain it)

arr[0] arr[1] arr[2]

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 25


Array of Pointer
▪ 2. what will happen after the code snipet:
arr[1] = arr[0];

Memory Leak

arr[0] arr[1] arr[2]

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 26


Array of Pointer: Deallocating
▪ To deallocate an array of pointers in C++, you need to free the memory
allocated for each pointer in the array
int* arr[3]; // Array of integer pointers
// Allocate the dynamic memory for each pointer
arr[0] = new int;
arr[1] = new int[2];
arr[2] = new int[4];

// deallocating the elements in array of pointer arr


delete arr[0]; arr[0] = NULL;
delete[] arr[1]; arr[1] = nullptr;
delete[] arr[2]; arr[2] = 0;

 delete[] arr; //arr is a static variable, we don’t need to delete it


Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 27
Pointer to Pointer (Double Pointer)
▪ A pointer to pointer in C++ is essentially a variable that stores the
address of another pointer.
int a = 10;
int* p1 = &a;
int** p2 = &p1;
cout << "Addr of a: " << p1 << endl;
cout << "Addr of p1: " << p2 << endl;
cout << "Val of a (via p1): " << *p1 << endl;
cout << "Val of a (via p2): " << **p2 << endl;
p2 p1 a
0x61ff04 0x61ff08 10

0x61ff04 0x61ff08
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 28
Double Pointer
▪ Draw a pointer diagram for the following code snipet:
int** ptr;
ptr = new int*;
*ptr = new int[5];

ptr *ptr **ptr

▪ How to init the value “4” in the **ptr?

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 29


Double Pointer
▪ Draw a pointer diagram for the following code snipet:
int** ptr; **ptr
ptr *ptr
ptr = new int*;
2
*ptr = new int[5];
▪ How to init the value “2” in the **ptr?
▪ ptr[0][2] = 4;
▪ *(ptr[0] + 2) = 4;
▪ *(*ptr + 2) = 4;
▪ **ptr + 2 = 4; ??? -> Operator Precedence

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 30


Double Pointer
▪ We can use double pointer to allocate an array of pointers dynamically
int** ptr;
//allocate an array of 4 pointers dynamically
ptr = new int*[4];
ptr[0] = new int[1];
ptr[1] = new int[2];
ptr[2] = new int[4];
ptr[3] = new int[6];

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 31


Double Pointer - Deallocate
▪ When deallocating memory associated with a double pointer, or a pointer
of a higher order, in C++, it is essential to adhere to the principle of
"Deallocating from the innermost allocation outward.“

for (int i = 0; i < 4; ++i)


delete[] ptr[i];

delete[] ptr;
ptr = NULL;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 32


Usages of Array of Pointers
▪ Dynamic memory allocation
▪ Arrays of strings
const char* strs[] = {"I", "am", "a", "student"};
▪ Multi-dimensional arrays
int* arr[NROW];
for (int i = 0; i < NROW; i++)
arr[i] = new int[NCOL];
▪ Pointers to functions
▪ Data structures: Arrays of pointers are often used to store pointers to
data structures Student* pStudents[100];

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 33


Usages of Pointer to Pointer
▪ Dynamic memory allocation: 2-D Array
▪ Pointer parameters to functions that need to modify a pointer variable
void createList(ListNode** head);
▪ Creating an array of pointers
int** arr;
arr = new int*[NROW];
for (int i = 0; i < NROW; i++)
arr[i] = new int[i + 1];

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 34


Pointers to Functions

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 35


Pointers to Functions
▪ Obtain the address of a function
▪ Declare a pointer to a function
▪ Use a pointer to invoke the function

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 36


Pointers to Functions
▪ Functions, like data items, have addresses
▪ A function’s address is the memory address at which the stored
machine language code for the function begins
▪ It’s possible to write a function that takes the address of another
function as an argument.
▪ It leaves open the possibility of passing different function addresses at
different times

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 37


Pointers to Functions
▪ To obtain the address of a function, just use the function name without
trailing parentheses
▪ If func() is a function, then func is the address of the function
▪ To pass a function as an argument, you pass the function name
▪ Notes:
//pass the address of func() to process01()
process01(func);
//pass the return value of func() to process02()
process02(func());

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 38


Pointers to Functions
▪ A pointer to a function has to specify to what type of function the pointer
points:
▪ the function’s return type
▪ the function’s argument list
▪ Consider the following prototype:
double square_root(int); //prototype
double exponent(int); //prototype

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 39


Pointers to Functions
▪ A pointer to a function has to specify to what type of function the pointer
points:
▪ the function’s return type
▪ the function’s argument list
▪ Consider the following prototype:
double square_root(int); //prototype
double exponent(int); //prototype
▪ Two of the above functions has the “similar” prototype as:
▪ Return: 1 double value
▪ Input: 1 integer number
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 40
Pointers to Functions
▪ Therefore, the corresponding pointer must satisfy the above
characteristics:

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 41


Pointers to Functions
▪ Consider the function prototype:
//pf points to a function that takes one int
double (*pf) (int);
//argument and returns a double type
▪ Note:
▪ Parentheses have a higher precedence than the * operator
//func is a function that returns a pointer
double* func(int);
▪ Declare a function pointer:

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 42


Pointers to Functions
▪ Write the declaration for the pointers to the following function
▪ void swap(int& a, int& b);

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 43


Pointers to Functions
▪ Write the declaration for the pointers to the following function
▪ void swap(int& a, int& b);
▪ void (*ptr)(int&, int&);

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 44


Pointers to Functions
▪ Using a Pointer to Invoke a Function
▪ (*ptr) plays the same role as a function name. Thus, all you have to
do is use (*pf) as if it were a function name
void swap(int& a, int& b){
int tmp = a; a = b; b = tmp;
}
void (*ptr)(int&, int&);
ptr = swap;
int n = 5, m = 10;
(*ptr)(n, m);
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 45
Case Study: Pointers to Functions
▪ Think about the sorting algorithm, for example: selection sort
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
// Move through the unsorted array
for (i = 0; i < n-1; i++) {
// Find the minimum element in the unsorted array
minIndex = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;

// Swap the found minimum element with the first element


swap(arr[minIndex], arr[i]);
}
}
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 46
Case Study: Pointers to Functions
void selectionSort_ver2(int arr[], int n, bool (*compare)(int, int)) {
for (int i = 0; i < n - 1; i++) {
// Find the extreme element depending on the comparator
int extremeIndex = i;
for (int j = i + 1; j < n; j++) {
if (compare(arr[extremeIndex], arr[j])) {
extremeIndex = j;
}
}
// Swap the found extreme element with the first element
swap(arr[extremeIndex], arr[i]);
}
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 47


Case Study: Pointers to Functions
// Comparator function for ascending order
bool ascending(int a, int b) {
return a > b;
}

// Comparator function for descending order


bool descending(int a, int b) {
return a < b;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 48


Exercise
1. Write a C++ function to get all starting and ending index
of all subarrays that has sum of elements equals to S
int** segmentList(int* arr, int n, int S, int& subarr_size);

For example,
Input array: {1, 2, 3, 2, 2, 2, 3, 1, 5}, S = 6
Return list: { (0, 2), (3, 5), (5, 7), (7,8) },
subarr_size = 4

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 49


Exercise
2. Diagonal Sum of a Square Matrix:
int diagonalSum(int** matrix, int size);

For example,
Input array: { {1, 5, 8}, {4, 3, 1}, {6, 5, 2}
Output: 6

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 50


Exercise
3. Sort each row of a dynamically allocated 2D array:
void sortRows(int** mat, int nRow, int nCol);

For example,
Input array: [[3, 2, 1], [6, 5, 4]]
Output: [[1, 2, 3], [4, 5, 6]]

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 51


Exercise
4. Merge two sorted dynamically allocated arrays into a
single sorted array:
int* mergeAndSortArrays( int* arr1, int size1,
int* arr2, int size2);

For example,
Input array:[1, 3, 5] and [2, 4, 6]
Output: [1, 2, 3, 4, 5, 6]

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 52


Exercise
5. What is the output of the following snipet:
char* ptr;
char str[] = "ABCD";
ptr = str;
cout << ptr++;
cout << ++ptr;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 53


Exercise
6. What is the output of the following snipet:
char* ptr;
char str[] = "ABCD";
ptr = str;
while (*ptr){
ptr++;
cout << ptr;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 54


THANK YOU
for YOUR ATTENTION

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 55

You might also like