0% found this document useful (0 votes)
4 views51 pages

2023 Slot03 Pointer

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)
4 views51 pages

2023 Slot03 Pointer

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/ 51

University of Science – VNU-HCM

Faculty of Information Technology


CSC10002 – Programming Techniques

Session 03 -
Pointer & Dynamic Memory
Instructor:
Dr. LE Thanh Tung

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 1


Content

1 Pointer
2 Dynamic Memory: Pointer, Array and String
3 Pointer Exercises

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 2


Pointer
▪ Pointer variables are an important concept and one that’s traditionally
difficult to grasp at first
▪ Programming with pointer variables in C/C++ is a double-edge sword
▪ They can be extremely useful and flexible CON DAO HAI LUOI

▪ Misuses of pointers can lead to both bizarre effects and very subtle
errors

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 3


Random Access Memory
▪ A computer’s memory, also
known as random access
memory (RAM), consists of
a sequence of bytes
▪ Each byte of memory has a
unique address
▪ Physically, computer
addresses start with
zero and continue up,
one at a time, until they
reach the highest
address
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 4
Variable in C
▪ The following diagram
illustrate the relationship
between computers'
memory address and
content; and variable's
name, type and value
used by the
programmers

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 5


Reference Operator
▪ sizeof (val/type) → the size in bytes of operands
▪ Operator “&” called the address-of (or address) operator
▪ In practice, we do not need to know or use (modify) the physical
address of a variable

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 6


Reference Operator
▪ Memory address of a variable is the location where the variable is stored
on the computer
▪ In the pass-by-reference examples, the & operator is used to create a
reference variable (i.e., to get the memory address of a variable)
int main(){
int a = 50;
cout << "Value = " << a << endl;
cout << "Address = " << &a << endl;
// Value = 50
// Address = 0x61ff0c
return 0;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 7


Reference Operator
int main(){
int a = 50;
cout << "Value = " << a << endl;
cout << "Address = " << &a << endl;
// Value = 50
// Address = 0x61ff0c Address:
return 0; 0x61ff0c
}
50
How to store the address of a ???
int a = 50;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 8


Pointer
▪ A pointer variable (pointer) is a is simply a new type of variable
▪ store the memory address
▪ allows pointers to directly access and manipulate the particular
memory location

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 9


Pointer
▪ We can have pointers to (one or more)
▪ Integers
▪ floating point
▪ characters
▪ structures
▪ objects of a class
▪ Each represents a different type of pointer

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 10


Pointer
▪ Declaration:
data_type *ptr; // same as data_type* ptr;
▪ Read this variable definition from right to left
▪ ptr is a pointer (that is what the * means) to a variable
▪ this means ptr can contain the address of some other
variables

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 11


Why we need pointer
▪ They are essential for allowing us to use data structures that grow and
shrink as the program is running
▪ Dynamic Memory Allocation
▪ Passing by Reference
▪ Building Complex Data Structures
▪ In this course, we will explore complex data structures like Linked Lists,
Stacks, Queues, and more.
→ move beyond the limitations of fixed-size arrays and handle data more
dynamically and efficiently

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 12


Pointer
▪ But first,
▪ 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;
▪ if an object is a list of names...then the size of that list can be
determined dynamically while the program is running.
▪ This cannot be accomplished in a user friendly way with
simple arrays!

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 13


Pointer
▪ So, what are the data types for the following variables?
int main(){
int a = 10;
int* ptr1, obj1; //watch out!
obj1 = a;
cout << "obj1(a) = " << obj1 << endl;
obj1 = &a;
cout << "obj1(&a) = " << obj1 << endl;
return 0;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 14


Pointer
▪ So, what are the data types for the following variables?
int main(){
int a = 10;
int* ptr1, obj1; //watch out!
obj1 = a;
cout << "obj1(a) = " << obj1 << endl;
obj1 = &a; <-- Error Here
cout << "obj1(&a) = " << obj1 << endl;
return 0;
}

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 15


Pointer
▪ How about these?
char* ptr2, *ptr3;
float obj2, *ptr4;
▪ What are their initial values?

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 16


Pointer
▪ The best initial value for a pointer is
▪ zero (address zero)
▪ also known as NULL (this is a #define constant in the
iostream library for the value zero!)
▪ The following accomplish the same thing:
int *ptr1 = NULL;
int *ptr2 = nullptr; // From C++ 11
int *ptr3 = 0;
int *ptr4 (0);
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 17
Allocating Memory
▪ You can allocate memory dynamically (as our programs are
running)
▪ and assign the address of this memory to a pointer variable
int *ptr1 = new int;

?
ptr1
dynamic variable
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 18
Pointer
▪ The diagram used is called a
▪ pointer diagram
▪ it helps to visualize what memory we have allocated and what our
pointers are referencing
▪ notice that the dynamic memory allocated is of size int in this case
and, its contents is uninitialized
▪ new is an operator and supplies back an address of the memory set
allocated

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 19


Dereferencing
▪ so we have learned how to set up a pointer variable to point to
another variable or to point to memory dynamically allocated.
▪ But, how do we access that memory to set or use its value?
▪ By dereferencing “*” our pointer variable
▪ *ptr1 = 10;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 20


Allocating Memory
▪ Let's examine a snippet of C++ code that has a potential risk
factor
int *ptr1;
ptr1 = new int; 10
*ptr1 = 10; ptr1
// code dynamic variable
cout << *ptr1;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 21


Deallocating
▪ Once done with dynamic memory
▪ we must deallocate it
▪ C++ does not require systems to do “garbage collection” at
the end of a program’s execution!
▪ We can do this using the delete operator:
delete ptr1;
▪ this does not delete the pointer variable

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 22


Deallocating
▪ this does not delete the pointer variable
▪ Instead, it deallocates the memory referenced by this pointer
variable
▪ It is a no-op if the pointer variable is NULL
▪ It does not reset the pointer variable
▪ Must reset the pointer to NULL
▪ It does not change the contents of memory
▪ Only free (release) the memory location to OS
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 23
Allocating Arrays
▪ By allocating arrays dynamically
▪ we can wait until run time to determine what size the array
should be
▪ the array is still “fixed size” … but at least we can wait until
run time to fix that size
▪ this means the size of a dynamically allocated array can be a
variable

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 24


Allocating Arrays
▪ First, let’s remember what an array is

int arr[10] = {1, 2, 3, 4};


cout << "a0 = " << arr[0] << endl;
cout << "a = " << arr << endl;
cout << "&a[0] = " << &arr[0];

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 25


Allocating Arrays
▪ First, let’s remember what an array is

int arr[10] = {1, 2, 3, 4};


cout << "a0 = " << arr[0] << endl; // a0 = 1
cout << "a = " << arr << endl; // a = 0x61fed8
cout << "&a[0] = " << &arr[0]; // &a[0] = 0x61fed8

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 26


Allocating Arrays
▪ First, let’s remember what an array is
▪ the name of an array is a constant address to the first
element in the array

int arr[10] = {1, 2, 3, 4};


cout << "a0 = " << arr[0] << endl; // a0 = 1
cout << "a = " << arr << endl; // a = 0x61fed8
cout << "&a[0] = " << &arr[0]; // &a[0] = 0x61fed8

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 27


Allocating Arrays
▪ To dynamically allocate an array
▪ must define a pointer variable to contain an address of the element
type
▪ Next, we can allocate a memory location for a lot of values
int size = 4; //for example
char *char_ptr;
char_ptr = new char [size];

char_ptr
4 characters
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 28
Allocating Arrays
▪ How to use the dynamic array
→ in the exact same way we do for any array

char_ptr[index] = 'a'; //or


cin.get(char_ptr,4,'\n');

char_ptr
4 characters
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 29
Allocating Arrays
▪ The only difference is when we are finally done with the array
▪ Deallocation for array: delete [] char_ptr;

char_ptr
4 characters

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 30


Allocating Arrays
▪ One of the common errors we get
▪ once allocating memory dynamically is a segmentation fault
▪ it means you have accessed memory that is not yours
▪ you have dereferenced the null pointer
▪ you have stepped outside the array bounds
▪ or you are accessing memory that has already been
deallocated

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 31


Pointer Arithmetic
▪ When we use the subscript operator
▪ pointer arithmetic is really happening
▪ this means the following are equivalent
ptr1[3] == *(ptr1+3)
▪ This means the subscript operator adds the value of the
index to the starting address and then dereferences the
quantity

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 32


Pointer Arithmetic
▪ Some arithmetic operations, such as addition or subtraction,
may be performed on pointer variables
▪ Adding one to a pointer variable increases its value by the size
(in byte) of the type to which it points

int arr[5] = {1, 2, 3, 4, 5};


int* ptr = &arr[2];
cout << *(ptr + 2) << endl;
cout << *(ptr - 1) << endl;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 33


Pointers and Arrays
▪ This identity means that the subscript operation is equivalent to adding
the index to the pointer expression and then dereferencing the result
▪ Understanding this identity allows us to decompose array subscripting
operations into pointer operations
▪ Array and pointer operations can be the same, even though the
declarations for arrays and pointers are different
arr[3] = 42; //this stores 42 w/array subscripting
*(arr + 3) = 42; //same thing using pointer operations
*(3 + arr) = 42; //addition is communitive

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 34


Pointers and Arrays
▪ Walk through the following in class
int a[10];
int* p=a; //initialize p to &a[0]
int* q=&a[2]; //initialize q to &a[2]
p = q; //assign q to p

p = &a[5]; //p points to the 6th element &a[5]


p+=3; //p now points to the 9th element &a[8]
p-=8; //p now points to the 1st element &a[0]

p = &a[5]; //p points to the 6th element &a[5]


++p; //p now points to the 7th element &a[6]
p++; //p now points to the 8th element &a[7]
p = p + 2; //p now points to the 10th element &a[9]
--p; //p now points to the 9th element &a[8]
p--; //p now points to the 8th element &a[7]
p = p - 2; //p now points to the 6th element &a[5]
q = ++p; //p,q now points to the 7th element &a[7]
q = p++; //p now points to the 8th element &a[8]
// but q points to the 7th element
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 35
Pointers and Arrays
▪ Walk through the following in class
int a[10];
int* p=a; //initialize p to &a[0]
int* q=&a[2]; //initialize q to &a[2]
p = q; //assign q to p

p = &a[5]; //p points to the 6th element &a[5]


p+=3; //p now points to the 9th element &a[8]
p-=8; //p now points to the 1st element &a[0]

p = &a[5]; //p points to the 6th element &a[5]


++p; //p now points to the 7th element &a[6]
p++; //p now points to the 8th element &a[7]
p = p + 2; //p now points to the 10th element &a[9]
--p; //p now points to the 9th element &a[8]
p--; //p now points to the 8th element &a[7]
p = p - 2; //p now points to the 6th element &a[5]
q = ++p; //p,q now points to the 7th element &a[7]
q = p++; //p now points to the 8th element &a[8]
// but q points to the 7th element
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 36
Pointer Arithmetic
▪ There are two key points in understanding pointer arithmetic.
▪ The first is that pointer variables can be modified whereas array names
are constants and cannot be modified.
▪ The second is that pointer operations automatically take into account
the size of the data pointed to, just like array subscripts do.
▪ This means that operations such as addition and subtraction are
independent of the size of the data.
▪ When we add one to a pointer of some type, we point to the next
element of that type

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 37


Pointer Arithmetic
▪ Walk through the following in class
int a[10];
int* p=a; //define and initialize p to &a[0]
p = p + 1; //add 1 to p; p==&a[1]
*p = *p + 1; //(*p)=(*p)+1; add 1 to a[1]
*p = *(p + 1); //copy a[2] to a[1]
p+=1; //add 1 to p; p==&a[2]
*p+=1; //(*p)+=1; add 1 to a[2]
*(p+=1); //add 1 to p; p==&a[3]
++p; //add 1 to p; p==&a[4]
++*p; //derefer p; add 1 to a[4]
*++p = 100; //add 1 to p; p==&a[5], a[5] = 100
p++; //add 1 to p; p==&a[6]
*p++ = 200; //*(p++); a[6]=200; add 1 to p; p==&a[7]
(*p)++; //dereference p;
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 38
Pointer Arithmetic
▪ Walk through the following in class
int a[10];
int* p=a; //define and initialize p to &a[0]
p = p + 1; //add 1 to p; p==&a[1]
*p = *p + 1; //(*p)=(*p)+1; add 1 to a[1]
*p = *(p + 1); //copy a[2] to a[1]
p+=1; //add 1 to p; p==&a[2]
*p+=1; //(*p)+=1; add 1 to a[2]
*(p+=1); //add 1 to p; p==&a[3]
++p; //add 1 to p; p==&a[4]
++*p; //derefer p; add 1 to a[4]
*++p = 100; //add 1 to p; p==&a[5], a[5] = 100
p++; //add 1 to p; p==&a[6]
*p++ = 200; //*(p++); a[6]=200; add 1 to p; p==&a[7]
(*p)++; //dereference p;
Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 39
Arrays of Arrays
▪ Arrays can be formed from any type of data, even other arrays
▪ When each element is an array, we define an array of arrays
▪ With an array of arrays, each element is an array of some type.
▪ Arrays of arrays are sometimes called multidimensional arrays in C++.
▪ This is not strictly correct because each dimension represents a different
type, rather than each dimension representing the same type

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 40


Arrays of Arrays
▪ To access elements of an array of arrays, we can use the subscript
operator. To access the appropriate subarray, we follow the name of the
array by an index in brackets. For example, array[0] accesses the first
subarray. The value of this element is the first subarray of two integers.
Its type is an array of integers (a pointer to an int)
▪ To access elements within a subarray, we follow the name of the array by
the index of the subarray in brackets and then follow that by the index
of the element within the subarray that we wish to access in brackets.
For example, array[0][0] accesses the first integer in the first
subarray

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 41


Arrays of Arrays
▪ The name of an array of arrays also represents a pointer expression. By
itself, it has a value equal to the address of the first element of the array.
The type is a pointer to the first element of the array.
▪ For example, the type of array is
int (*)[2]; // a pointer to an array of two integers

int array[3][2];
int (*p1)[2]; //define pointer of same type as array
p1 = array; //assign pointer to point to array

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 42


Arrays of Arrays
▪ Walkthrough the following code:
int array[3][2] = { {1, 2}, {3, 4}, {5, 6}};
int (*p1)[2]; //define pointer of same type as array
p1 = array; //assign pointer to point to array
int *p; //define ptr of same type as subarray
p = *p1; //assign ptr to point to 1st subarray
p = array[0]; //this also points to 1st subarray and
p = *(array+0); //so does this because of our identity
p = *array; //and so does this

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 43


Arrays of Arrays
▪ Walkthrough the following code:
int array[3][2] = { {1, 2}, {3, 4}, {5, 6}};
int (*p1)[2]; //define pointer of same type as array
p1 = array; //assign pointer to point to array
int *p; //define ptr of same type as subarray
p = *p1; //assign ptr to point to 1st subarray
p = array[0]; //this also points to 1st subarray and
p = *(array+0); //so does this because of our identity
p = *array; //and so does this

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 44


Arrays of Arrays

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 45


Pointers and Strings
▪ Consider the following code:
char flower[10] = "rose";
cout << flower << "s are red\n";
▪ cout assumes that the address of a char is the address of a string, so it
prints the character at that address and continues printing characters
until it runs to a null character
▪ This implies that you can use a pointer-to-char variable as an argument
to cout because it is also the address of a character

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 46


Pointers and Strings
char animal[20] = "bear"; //animal holds bear
const char* bird = "pigeon"; //initialize a pointer-to-char
//to a string -> assign the address
//of pigeon to pointer bird
char* ps; // uninitialized
ps = animal; // set ps to point to string
cout << animal << "\n"; // display bear
cout << bird << "\n"; // display pigeon
cout << ps << "\n" ; // display bear

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 47


Pointers and Strings
char animal[20] = "bear"; //animal holds bear
char *ps = animal;
cout << ps; // display the string
cout << (int* ) ps; // display the address of string

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 48


Pointers and Strings
char animal[20] = "bear";
int len = strlen(animal) + 1;
char* ps = new char[len]; // get new storage
strcpy(ps, animal); // copy string to new storage
cout << animal << " is at " << (int *) animal << endl;
cout << ps << " now is at " << (int *) ps << endl;

delete[] ps;

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 49


Exercise
1. Write a C++ function to swap two integers using pointers
void Swap(int* a, int* b);
2. Develop a program to reverse a string using pointers
void Reverse(char* str);
3. 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 50
THANK YOU
for YOUR ATTENTION

Dr. LE Thanh Tung CSC10002 – Programming Techniques Page 56

You might also like