Act 2 Arrays Pointers and Dynamic Memory Allocation
Act 2 Arrays Pointers and Dynamic Memory Allocation
2
ARRAYS, POINTERS AND DYNAMIC MEMORY ALLOCATION
Course Code: CPE010 Program: Computer Engineering
Course Title: Data Structures and Algorithms Date Performed:
Section: Date Submitted:
Name: Instructor: Engr. Roman M. Richard
1. Objective(s)
Demonstrate the use of dynamic memory allocation
3. Discussion
Part A: Variables
Typical Variable Declaration
int x = 10;
Using the assignment operator, assign the value 10 to the memory address represented by x. During
compilation, this variable name is translate to the memory address.
int x = 10;
std::cout << x << std::endl;
std::cout << &x << std::endl;
int x = 10;
std::cout << x << std::endl;
std::cout << &x << std::endl;
std::cout << *&x << std::endl;
Part B: Pointers
Simply put, a pointer is a variable that has the address of a memory location that contains data.
0x654321 0x123456
0x123456 10
Pointer Pointee
9
To declare the pointer:
- Indicate the variable type
- Put the dereference operator
- Put the name of the variable
type *var_name
int *intPtr
double *dbPtr
int pointee = 10
int *pointer = &pointee
nullptr
When a pointer points to nothing, the keyword nullptr is used.
0x654321
0x0
Pointer
C++ Memory
Code
This code creates a pointer called array so that we can access the elements inside the array. The compiler
knows that when the [] syntax is used, there will be an array of integer values. This syntax also makes it so
that such arrays are declared const. Example:
Arrays declared with [] against those using pointers is that the ones declared using pointers can be
reassigned, but not the arrays declared with [].
Accessing these arrays on the heap is done the same way as before:
array[index];
delete ptr;
General rule of thumb: for every new operator you must have a delete operation. This is to avoid a memory
leak, which is caused by the failure to de-allocate memory that is pointed to by a pointer. This is caused by
common mistakes such as:
While in a loop, allocating memory but using delete on the pointer out of scope.
Forgetting to delete data inside an object that is dynamically allocated.
11
This delete operator is followed by a [] to indicate that we are deleting a block of memory.
class Student{
public:
string obj_name;
Student(string name="John Doe"){
obj_name = name;
}
};
This allocates a space for the Student object in the heap then calling the default constructor. Alternatively, you
can pass an argument to the constructor, such that:
Now, to access the data members of the class as shown in the code above. We can do the following:
a->data_member;
a->function();
These also follow a good practice in programming that we call the rule of three. If you have to define one,
define all of them.
Destructors
This member function is called that deletes an object. Some of the situations wherein we call destructors are
when a function ends, when the program ends, when a block that contains local variables end, or when a
delete operator is called. For every class, we have one destructor. Syntax is shown below:
Student::~Student(){
/* Clean the data */
12
}
Copy Constructor
A copy constructor makes a copy of an existing instance. If we do not define the copy constructor, it is
defined implicitly by the compiler per member of the source object.
It is important that we declare a copy constructor by passing in the class we want to copy as const.
Student::Student(const Student ©Student) {
...
}
The most common use for the copy constructor is when the class has raw pointers as member variables and
we need to make a deep copy of the data.
5. Procedure
ILO A: Implement static and dynamic memory allocation & ILO B: Create dynamically allocated objects
using pointers and arrays
In this activity, we will explore static and dynamic memory allocation through by utilizing arrays and other
components mentioned beforehand, this will be for the implementation of a student list with the students’
names and age. To begin, we will include pertinent libraries for input/output stream and strings (which we will
be using in this activity).
#include <iostream>
#include <string.h>
Now we will create the student class with private attributes studentName and studentAge.
class Student{
private:
std::string studentName;
int studentAge;
13
Then, as discussed beforehand, we have to define the constructor and the big three: the destructor, copy
constructor and copy assignment operator. We will assign default values for the parameters of our
constructor in the event that it is uninitialized.
public:
//constructor
Student(std::string newName ="John Doe", int newAge=18){
studentName = std::move(newName);
studentAge = newAge;
std::cout << "Constructor Called." << std::endl;
};
The big three is then defined. We will add an output stream for each to observe when each of the following
functions are implicitly or explicitly called.
//deconstructor
~Student(){
std::cout << "Destructor Called." << std::endl;
}
//Copy Constructor
Student(const Student ©Student){
std::cout << "Copy Constructor Called" << std::endl;
studentName = copyStudent.studentName;
studentAge = copyStudent.studentAge;
}
//Display Attributes
void printDetails(){
std::cout << this->studentName << " " << this->studentAge << std::endl;
}
};
The driver program is now to be defined. We want to utilize the main function to simply show the static and
dynamic allocation. However, we will explore the initial goal of creating instances of our Student class.
int main() {
Student student1("Roman", 28);
Student student2(student1);
Student student3;
student3 = student2;
return 0;
}
Run the code and show the output. Include the screenshot in table 2-1 followed by your observation.
Now, modify the driver program so that we have the array size of 5, an array of Student objects, the list of
students’ names and their age.
int main() {
const size_t j = 5;
Run the code with the modified driver function and show the output. Include the screenshot in table 2-2
followed by your observation.
We have so far created static memory allocation through the use of the arrays. We will now dynamically
allocate instances of the student class and store the newly created objects in the locations pointed to by our
array.
int main() {
const size_t j = 5;
return 0;
}
Discuss what is done by loop A and loop B in table 2-3. Additionally, discuss the output and whether the
functions are working as intended. If any corrections were made, further provide your modification and
analysis in table 2-4.
6. Output
Screenshot
Observation
Table 2-1. Initial Driver Program
Screenshot
Observation
Table 2-2. Modified Driver Program with Student Lists
Loop A
Observation
Loop B
Observation
Output
Observation
Table 2-3. Final Driver Program
15
Modifications
Observation
Table 2-4. Modifications/Corrections Necessary
7. Supplementary Activity
ILO C: Solve programming problems using dynamic memory allocation, arrays and pointers
Jenna wants to buy the following fruits and vegetables for her daily consumption. However, she needs to
distinguish between fruit and vegetable, as well as calculate the sum of prices that she has to pay in total.
Problem 1: Create a class for the fruit and the vegetable classes. Each class must have a constructor,
deconstructor, copy constructor and copy assignment operator. They must also have all relevant attributes
(such as name, price and quantity) and functions (such as calculate sum) as presented in the problem
description above.
Problem 2: Create an array GroceryList in the driver code that will contain all items in Jenna’s Grocery List.
You must then access each saved instance and display all details about the items.
Problem 3: Create a function TotalSum that will calculate the sum of all objects listed in Jenna’s Grocery List.
Problem 4: Delete the Lettuce from Jenna’s GroceryList list and de-allocate the memory assigned.
8. Conclusion
Provide the following:
Summary of lessons learned
Analysis of the procedure
Analysis of the supplementary activity
Concluding statement / Feedback: How well did you think you did in this activity? What are your areas
for improvement?
9. Assessment Rubric
16