Lecture 14
Lecture 14
Algorithms 1
CHAPTER 6: DYNAMIC MEMORY
ALLOCATION
(POINTER ARRAY – LINKED LIST)
Sep – Dec 2023
Array of Pointers
Arrays can contain pointers
Commonly used to store array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds“, "Clubs", "Spades" };
Each element of suit points to char * (a string)
Array does not store strings, only pointers to strings
suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’
suit array has fixed size, but strings can be of any size
Pointers and Structs
Pointers can point to a struct or class
month 7
instance as well as to a regular variable.
0xa12
One way to do this would be to day 31
dereference and then use dot notation:
Date d;
d.month = 7;
Date* dPtr = &d;
cout << (*dPtr).month << endl;
dPtr
But, this notation is cumbersome, and the 0xa12
parenthesis are necessary because the "dot" has a
0x77
higher precedence than the *.
Pointers and Structs
So, we have a different, and more
month 7
intuitive syntax, called the "arrow"
0xa12
syntax, ->
day 31
Date d;
d.month = 7;
Date* dPtr = &d;
cout << dPtr->month << endl;
dPtr
We will use the arrow syntax almost exclusively 0xa12
when using structs.
0x77
Pointers and Structs
The arrow syntax can be used to set a
month 7
value in a struct via a pointer, as well
0xa12
day 31
Date d;
d.month = 7;
Date* dPtr = &d;
cout << dPtr->month << endl;
dPtr->day = 1;
cout <<dPrtp->day << endl; // 1 dPtr
0xa12
0x77
Dynamic memory allocation
So far in this course, all variables we have seen have been local variables that
we have defined inside functions. Sometimes, we have had to pass in object
references to functions that modify those objects. For instance, take a look at
the following code:
struct Vector {
int data[100];
int size;
};
void squares(Vector &vec, int numSquares) {
for (int i = 0; i < numSquares; i++) {
vec.data[i] = i * i;
}
}
This function requires the calling function to create a struct to use inside the
function. This isn't necessarily bad, but could we do it a different way? In other
words, could we create the Vector inside the function and just pass it back?
Dynamic memory allocation
Could we create the Vector inside the function and just pass it back?
Vector squares(int numSquares) {
Vector vec;
for (int i = 0; i < numSquares; i++) {
vec.data[i] = i * i;
}
return vec;
}
firstPtr lastPtr
H D ... Q
struct Node {
int data;
Node * next;
};
Linked Lists
newPtr
12
b) firstPtr
7 11
newPtr
12
newPtr->next = firstPtr
firstPtr = newPtr
If list empty, then
firstPtr = lastPtr = newPtr
Insert at back
a) firstPtr lastPtr newPtr
12 7 11 5
12 7 11 5
lastPtr->next = newPtr
lastPtr = newPtr
If list empty, then
firstPtr = lastPtr =
newPtr
Remove from front
a) firstPtr lastPtr
12 7 11 5
b) firstPtr lastPtr
tempPtr = firstPtr
12 7 11 5
tempPtr
firstPtr = firstPtr->next
If there are no more nodes,
firstPtr = lastPtr = 0
delete tempPtr
Remove from back
a) firstPtr lastPtr
12 7 11 5
12 7 11 5
tempPtr = lastPtr
lastPtr =
currentPtr
tempPtr