CSNB244 - Lab 6 - Dynamic Memory Allocation in C++
CSNB244 - Lab 6 - Dynamic Memory Allocation in C++
In this lab session, you will learn on how to define the size of an array dynamically, allocate
/deallocate memory in a program, perform dynamic memory management.
new operator: dynamically allocate (i.e. reserve) the exact amount of memory required to
hold an object or array at execution time.
To return memories to the free store use the delete operator to deallocate (i.e. release) it.
int *ptr1 = new int;
...
delete ptr1;
int main()
{
int x=3;
int *xptr1 = &x;
int *xptr2 = new int;
*xptr2 = 10;
delete xptr2;
return 0;
}
int main()
{
fruit *localPtr = new fruit;
fruit *internationalPtr = new fruit;
delete localPtr;
delete internationalPtr;
}
Page 1 of 5
COIT – NSMS Nov 2013
Programming II with C++ (CSNB244) – Lab 6
Let’s see a real example.
#include <iostream>
#include <string>
using namespace std;
struct fruit {
char name[20];
float price;
};
int main()
{
fruit *localPtr = new fruit;
fruit *internationalPtr = new fruit;
cout << "I love to eat " << localPtr->name << endl;
cout << internationalPtr->name << " will cost me RM"
<< internationalPtr->price << " per kg." << endl;
delete localPtr;
delete internationalPtr;
return 0;
system("pause");
Page 2 of 5
COIT – NSMS Nov 2013
Programming II with C++ (CSNB244) – Lab 6
Full code example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int *ptr1 = new int(100);
delete ptr1;
return 0;
system("pause");
}
struct structName{
datatype variableInStruct1;
datatype variableInStruct3;
};
int main()
{
structName *arrayPtr = new structName[element]; //declare
variable. replace element with an integer
struct fruit {
char name[20];
float price;
};
int main()
{
fruit *localPtr = new fruit[SIZE];
int i;
delete localPtr;
return 0;
system("pause");
Page 4 of 5
COIT – NSMS Nov 2013
Programming II with C++ (CSNB244) – Lab 6
Lab Assignment (Carry Marks 5%)
There is a fruit shop name “Only Fresh Fruit Shop”. This shop sells the following fruits
and grouped by 2 different groups;
This shop has requested you to provide a program to calculate and provide the details
(receipt) of the purchase. You are required to use structure, pointer, and array to develop
this program. You may refer to the following figure to get as a sample of output. You may
also work in a group of 2 students per group.
You are required to show and explain this program to you lecturer on the next lab session.
Page 5 of 5
COIT – NSMS Nov 2013