0% found this document useful (0 votes)
53 views8 pages

LAB 2 DMA in Pointers

This is a lab manual for lab 2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views8 pages

LAB 2 DMA in Pointers

This is a lab manual for lab 2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

selection sort code searches an array looking for the smallest element in the array.

Then, the
smallest element is swapped with the first element of the array. The process is repeated for the
sub-array beginning with the second element of the array. Each pass of the array results in one
element being placed in its proper location. When the sub-array being processed contains one
element, the array is sorted. Write C++ code for this selection sort and output must be stored in
“output.txt” file (having all passes
selection sort code searches an array looking for the smallest element in the array. Then, the
smallest element is swapped with the first element of the array. The process is repeated for the
sub-array beginning with the second element of the array. Each pass of the array results in one
element being placed in its proper location. When the sub-array being processed contains one
element, the array is sorted. Write C++ code for this selection sort and output must be stored in
“output.txt” file (having all passes

School of Electrical Engineering and Computer Science


Department of Computing

CS250: Data Structure and Algorithms


Class: BSCS 13AB

Lab 2: Dynamic Memory Management with Pointers

Date: 16th September, 2024

Time: 09:00 am – 12:50 pm


and
02:00 pm – 04:50 pm

CS250: Data Structure and Algorithms Page 1


Instructor: Dr. Shams Qazi

Lab Engineer: Areeba Rameen

Recap:
Static vs Dynamic Arrays
Introduction:
In this lab, we will explore two ways of allocating memory for arrays in C++: static arrays and dynamic
arrays. Static arrays have a fixed size at compile time, while dynamic arrays can be resized at runtime
using dynamic memory allocation. Understanding these concepts is essential for effective memory
management and efficient program design.

Static Arrays (Method A):


A static array is created with a fixed size that is determined at compile time. Memory for static arrays is
allocated on the activation stack, and its lifetime depends on its scope:

Method A:
const int size=5;

int x[size];
for (int i = 0; i < size; i++)
{

x[i] = i + 1;
cout << "x[" << i << "] = "<< x[i] << endl;
}

Dynamic Arrays (Method B):


A dynamic array is created using the new operator at runtime, allowing you to specify its size during
execution.

Method B
int size; // Note that size variable is const in variant A whereas it isn’t in variant B. Find out the logic
behind it.

cout << "Enter size of array: ";

CS250: Data Structure and Algorithms Page 2


cin >> size;

int *x = new int[size];


for (int i = 0; i < size; i++)
{

x[i] = i + 1;
cout << "x[" << i << "] = "<< x[i] << endl;
}

TASK 1:
Write a function that asks the user to input the size of an array, allocates memory
dynamically for the array, and fills it with values from 1 to N (where N is the user-specified
size). Modify the function to free memory once the array is no longer needed.

Memory Management: new and delete


The process of allocating and deallocating memory is known as memory management. In C++,
memory management is crucial for optimizing performance and avoiding leaks. The new and
delete operators are used for dynamic memory allocation and deallocation, respectively.

new operator: Allocates memory for a variable or an array of variables dynamically.


Delete operator : deallocate dynamically allocated memory,
Syntax:
type* pointer = new type;
type* arrayPointer = new type[arraySize];
delete [] pointer;

Example:
int* ptr = new int; // Allocates memory for a single integer
*ptr = 10; // Assigns value to allocated memory
delete ptr; // Deallocates the memory

CS250: Data Structure and Algorithms Page 3


int* arr = new int[5]; // Allocates memory for an array of 5 integers
arr[0] = 1; // Assigns value to the first element

delete[] arr; // Deallocates the memory for the array

Example:
#include <iostream>
#include <cstring> //for strlen
using namespace std;
int main()
{
char* str = “Idle hands are the devil’s workshop.”;
int len = strlen(str); //get length of str
char* ptr; //make a pointer to char
ptr = new char[len+1]; //set aside memory: string + ‘\0’
strcpy(ptr, str); //copy str to new memory area ptr
cout << “ptr=” << ptr << endl; //show that ptr is now in str
delete[] ptr; //release ptr’s memory
return 0;
}
The expression
ptr = new char[len+1];
returns a pointer to a section of memory just large enough to hold the string str, whose length
len we found with the strlen() library function, plus an extra byte for the null character ‘\0’
at the end of the string.

TASK 2:

CS250: Data Structure and Algorithms Page 4


Write a C++ program that dynamically allocates an array of integers based on user input,
calculates and prints the sum and average of the array elements, and ensures proper
memory deallocation.

Pointers to Objects
In C++, pointers can point to objects just like they point to basic data types. This is useful when you don’t
know the exact number of objects you need at compile time. The new operator allows for dynamic object
creation, and the pointer can access the object’s members using the -> operator.
Example:
class Sample {
public:
void display() {
std::cout << “display” << std::endl;
}
};

Sample* objPtr = new Sample; // Dynamically creating an object


objPtr->display(); // Accessing member using pointer
Example:
#include <iostream>
using namespace std;

class Distance {
private:
int feet;
float inches;
public:
// Function to get distance input from the user
void getdist() {

CS250: Data Structure and Algorithms Page 5


cout << "\nEnter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
}

// Function to display the distance


void showdist() const {
cout << feet << "\'-" << inches << "\"" << endl;
}
};

int main() {
// Define a named Distance object
Distance dist;
dist.getdist(); // Get distance using dot operator
dist.showdist(); // Show distance using dot operator

// Create a pointer to a Distance object


Distance* distptr;
distptr = new Distance; // Points to a new Distance object
distptr->getdist(); // Get distance using pointer
distptr->showdist(); // Show distance using pointer

// Free the dynamically allocated object


delete distptr;

return 0;

CS250: Data Structure and Algorithms Page 6


}

Debugging Pointers
TASK 3:
Code
#include <iostream>
using namespace std;

int main() {
int* ptr = nullptr; // Pointer initialized to nullptr

// Try to dereference the pointer


cout << "Value pointed by ptr: " << *ptr << endl; // This will cause a crash

return 0;
}

Questions:
1) What happens when you try to dereference a null pointer, and why does the program
crash?
2) Modify the code to safely handle the null pointer and avoid the crash. What check would
you add?
3) What is the role of a nullptr in pointer safety, and why is it important to initialize pointers
with it?

TASK 4:
Develop a C++ program to model a Banking System with the following requirements:
1. Implement a base class `Account` that contains An `accountNumber` (int), A `balance` (double)
and customerName` (string)

CS250: Data Structure and Algorithms Page 7


Implement methods:
- A constructor to initialize these fields.
- A pure virtual method `deposit(double amount)` to deposit money into the account.
- A pure virtual method `withdraw(double amount)` to withdraw money.
- A method `displayInfo()` to display account details.

2. Create three derived classes:


- SavingsAccount:
- Has an `interestRate` (double) as an additional attribute.
- Override the `deposit()` method to calculate the interest.
- Implement `withdraw()` such that no withdrawal is allowed if the balance falls below a certain
minimum.
- CheckingAccount:
- Has an `overdraftLimit` (double).
- Implement `withdraw()` such that withdrawals beyond the balance are allowed up to the overdraft
limit.
- InvestmentAccount:
- Has an `investmentDuration` (int) and `riskFactor` (double).
- Override `deposit()` and `withdraw()` to handle risk-based profit/loss when depositing or
withdrawing.

3. Implement **operator overloading** to compare two accounts based on their balances (`>`, `<`,
`==`).

4. In the **main** function:


- Create objects for all three types of accounts.
- Perform deposit and withdraw operations.
- Compare the accounts using the overloaded operators.
- Use polymorphism to manage the different types of accounts through base class pointers.
- Ensure proper memory management using virtual destructors.

CS250: Data Structure and Algorithms Page 8

You might also like