Moizahmed 1812 D

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Object Oriented Programming

(CL1004)
LABORATORY MANUAL
Spring 2023

LAB 06
Pointer Arrays and Pointers to Structures
Engr. Nimra Fatima

________________________________________ __________ ___


STUDENT NAME ROLL NO SEC

______________________________________
LAB ENGINEER SIGNATURE & DATE
MARKS AWARDED: ___/10

NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (NUCES),


Pointer Arrays & Pointers to Structures LAB 06

ISLAMABAD

LAB 06 Pointer Arrays & Pointers to Structures

Lab Objectives:
1. To learn the difference and similarity between pointers and arrays.
2. Dynamic Memory Allocation
3. To learn the method of passing pointers to functions.
4. To learn pointers to structures

Software Required:
● Dev C++/ Visual Studio/VS Code

Introduction:
1. Recap Pointers
A pointer is a variable that stores address of another variable. This pointer essentially points to that
variable. Pointer can be used to access and change the value of variable it points to, by using the
dereference operator (*).
1. # include<iostream> Output:
2. using namespace std;
3. int main (){
4. int a=3;
5. int* ap;
6. ap = &a;
7. *ap = 5; 8.
8. cout<< a <<endl; 9.
9. cout<<&a <<endl; 10.
11.
10. cout<<ap<<endl ;
11. cout<< *ap<<endl;
12. return 0;}

2. Pointers and Arrays


Not only can a pointer store the address of a single variable, it can also store the starting address of an array.
Method 1:
Consider this example:

int arr [5];

cout<<arr<<endl;

/* Display the address of the first element of arr that is address of arr[0]. Here arr
is used as a pointer to store the starting address of an array. */

Method 2:
int *ptr;
int arr[5];

ptr = arr;
// store the address of the first element of arr in ptr

Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the first element of
the array in variable ptr.
Notice that we have used arr instead of &arr[0]. This is because both are the same.

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 2 of 3


Pointer Arrays & Pointers to Structures LAB 06

The addresses for the rest of the array elements are given by &arr[1], &arr[2], &arr[3], and &arr[4].
Point to Every Array Elements

Suppose we need to point to the fourth element of the array using the same pointer ptr.
Here, if ptr points to the first element in the above example then ptr + 3 will point to the fourth element. For
example,
int *ptr;
int arr[5];
ptr = arr;
ptr + 1 is equivalent to &arr[1];
ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];
Similarly, we can access the elements using the single pointer. For example,

// use dereference operator

*ptr == arr[0];

*(ptr + 1) is equivalent to arr[1];

*(ptr + 2) is equivalent to arr[2];

*(ptr + 3) is equivalent to arr[3];

*(ptr + 4) is equivalent to arr[4];

Suppose if we have initialized ptr = &arr[2]; then

ptr - 2 is equivalent to &arr[0];

ptr - 1 is equivalent to &arr[1];

ptr + 1 is equivalent to &arr[3];

ptr + 2 is equivalent to &arr[4];

Note: The address between ptr and ptr + 1 differs by 4 bytes. It is because ptr is a pointer to an int data.
And, the size of int is 4 bytes in a 64-bit operating system.

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 3 of 3


Pointer Arrays & Pointers to Structures LAB 06

Similarly, if pointer ptr is pointing to char type data, then the address between ptr and ptr + 1 is 1 byte. It is
because the size of a character is 1 byte.

Dynamic Memory Allocation


C++ allows us to allocate the memory of a variable or an array in run time. This is known as dynamic memory
allocation.
We can allocate and then deallocate memory dynamically using the new and delete operators respectively as
demonstrated in the following example.

// Example program for dynamic memory allocation


#include <iostream>
using namespace std;

int main()
{
int i, n;
int *arr;
cout << "How many numbers would you like to type? " << endl;
cin >> n;
arr = new int[n];
for (i = 0; i < n; i++)
{
cout << " Enter number " << i + 1 << " : " << endl;
cin >> arr[i];
}
cout << "You have entered following numbers : " << endl;
for (i = 0; i < n; i++)
cout << arr[i] << ", ";
delete[] arr;
arr = NULL;
return 0;
}

C++ Pointers to Structure

A pointer variable can be created not only for native types like (int, float, double etc.) but they can also be created
for user defined types like structure. Here is how you can create pointer for structures:

Example: Pointers to Structure

#include <iostream>
using namespace std;
struct Distance {
int feet;
float inch;
};

int main() {
Distance *ptr, d;
ptr = &d;
cout << "Enter feet: ";
cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;
cout << "Displaying information." << endl;
cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";
return 0;
}

Output
Enter feet: 4
Enter inch: 3.5

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 4 of 3


Pointer Arrays & Pointers to Structures LAB 06

Displaying information.
Distance = 4 feet 3.5 inches
In this program, a pointer variable ptr and normal variable d of type structure Distance is defined.
The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d. Then, the member
function of variable d is accessed using pointer.

Notes:
● Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch are equivalent.
Similarly, (*ptr).feet and d.feet are equivalent.
● However, if we are using pointers, it is far more preferable to access struct members using the -
> operator, since the . operator has a higher precedence than the * operator.
Hence, we enclose *ptr in brackets when using (*ptr).inch. Because of this, it is easier to make mistakes if both
operators are used together in a single code.
ptr->feet is same as (*ptr).feet
● ptr->inch is same as (*ptr).inch
Lab Tasks:

1. Dry Run this code:

#include <iostream>
using namespace std;
int main() { // Missing parentheses after "main"
int set[5] = {15, 30, 45, 60, 75};
int w = 10;
char* ch;
float* fl;
double* db;
int* ptr = &w;
int* ptr1;
char* ptr2;
float* ptr3;
double* ptr4;
int i = 1;
char c = 'a';
float f = 3.12;
double d = 3.1234;
db = &d;
fl = &f;
ptr = set; // "ptr" is already declared above, so remove "int"
cout << *ptr << endl;
for (int q = 3; q < 5; q++) {
cout << *(ptr + q) << endl; // Use "q" instead of incrementing "ptr"
}
cout << *(ptr + 2) << endl;
cout << *(ptr + 3) << endl;
cout << db << "\t" << *fl << endl; // Use "*fl" instead of "f1"
ptr1 = &i;
ptr2 = &c;
ptr3 = &f;
ptr4 = &d;
cout << *ptr1 << *ptr2 << *ptr3 << *ptr4 << endl; // Add "*" before each pointer variable
return 0; // Add a return statement

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 5 of 3


Pointer Arrays & Pointers to Structures LAB 06

2. Declare an array of fixed size as arr [5]. Show the address of each memory location
using pointer.

3. In the following program, use dynamic arrays instead of simple arrays.

#include <iostream>
#include <string>
using namespace std;
struct student
{
string roll_no;
string name;
float gpa;
};

int main()
{
int n = 5;
student st[5], temp; // Making student Record by creating array of structure Objects
// initializing values
st[0] = {"21i-1234", "Imran Khan", 3.50};
st[1] = {"21i-0539", "Wasim Akram", 2.28};
st[2] = {"21i-0867", "Shahd Afridi", 3.85};
st[3] = {"21i-0122", "Muhammad Kamran", 3.98};
st[4] = {"21i-0324", "Naveed Akram", 2.35};

//? printing values

cout << "\n";


cout << "Roll_No \t"
<< "Name \t \t"
<< "GPA \t \n"
<< endl;
for (int i = 0; i < 5; i++)
{
cout << st[i].roll_no << "\t" << st[i].name << "\t" << st[i].gpa << "\n \n";
}
}

● Now sort the student array in the above program based on the GPA, and print the
sorted data.

● Now make a function and take your sorting code in this function. No global variable is
allowed. Think of the parameters and return type for this function before you code
that.

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 6 of 3


Pointer Arrays & Pointers to Structures LAB 06

4. Take an alphabet either lowercase or uppercase from user, and store the next
characters in two arrays.
The two arrays should be created dynamically with size only as much as needed. At the
end print the arrays as shown below.

TASK#2
INPUT:

#include <iostream>
using namespace std;
int main() {
int arr[5]={1,2,3,4,5};
int* ptr = arr;
for (int i = 0; i < 5; i++) {
cout << "Address of arr[" << i << "]: " << ptr+i << endl; }
return 0;}

OUTPUT:

TASK#3(a)
INPUT:

#include <iostream>
#include <string>
using namespace std;

struct student
{ string roll_no;
string name;
float gpa;};

int main()
{ int n = 5;
student* st = new student[n];
st[0] = {"21i-1234", "Imran Khan", 3.50};
st[1] = {"21i-0539", "Wasim Akram", 2.28};

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 7 of 3


Pointer Arrays & Pointers to Structures LAB 06

st[2] = {"21i-0867", "Shahd Afridi", 3.85};


st[3] = {"21i-0122", "Muhammad Kamran", 3.98};
st[4] = {"21i-0324", "Naveed Akram", 2.35};
cout << "\n";
cout << "Roll_No \t"
<< "Name \t \t"
<< "GPA \t \n"
<< endl;
for (int i = 0; i < n; i++)
{ cout << st[i].roll_no << "\t" << st[i].name << "\t" << st[i].gpa << "\n \n";}
delete[] st;
return 0;}

OUTPUT:

Task#3 (b)
INPUT:

#include <iostream>
#include <string>
using namespace std;

struct student
{ string roll_no;
string name;
float gpa;};

int main()
{ int n = 5;
student st[5] = {
{"21i-1234", "Imran Khan", 3.50},
{"21i-0539", "Wasim Akram", 2.28},
{"21i-0867", "Shahd Afridi", 3.85},
{"21i-0122", "Muhammad Kamran", 3.98},
{"21i-0324", "Naveed Akram", 2.35}};
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (st[j].gpa > st[j+1].gpa) {
student temp = st[j];

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 8 of 3


Pointer Arrays & Pointers to Structures LAB 06

st[j] = st[j+1];
st[j+1] = temp;}}}
cout << "\n";
cout << "Roll_No \t"
<< "Name \t \t"
<< "GPA \t \n"
<< endl;
for (int i = 0; i < n; i++)
{ cout << st[i].roll_no << "\t" << st[i].name << "\t" << st[i].gpa << "\n \n";}
return 0;}

OUTPUT:

TASK#3 (C)
INPUT:

#include <iostream>
#include <string>
using namespace std;

struct student
{ string roll_no;
string name;
float gpa;};

student* sort_students_by_gpa(student* st, int n) {


student* sorted_st = new student[n];
for (int i = 0; i < n; i++) {
sorted_st[i] = st[i]; }
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (sorted_st[j].gpa > sorted_st[j+1].gpa) {
student temp = sorted_st[j];
sorted_st[j] = sorted_st[j+1];
sorted_st[j+1] = temp;}}}
return sorted_st;}

int main()

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 9 of 3


Pointer Arrays & Pointers to Structures LAB 06

{ int n = 5;
student st[5] = {
{"21i-1234", "Imran Khan", 3.50},
{"21i-0539", "Wasim Akram", 2.28},
{"21i-0867", "Shahd Afridi", 3.85},
{"21i-0122", "Muhammad Kamran", 3.98},
{"21i-0324", "Naveed Akram", 2.35}};
student* sorted_st = sort_students_by_gpa(st, n);
cout << "\n";
cout << "Roll_No \t"
<< "Name \t \t"
<< "GPA \t \n"
<< endl;
for (int i = 0; i < n; i++)
{ cout << sorted_st[i].roll_no << "\t" << sorted_st[i].name << "\t" << sorted_st[i].gpa <<
"\n \n";}
delete[] sorted_st;
return 0;}

OUTPUT:

TASK#4

INPUT:

#include <iostream>
using namespace std;

int main() {
char alpha;
cout << "Enter an alphabet: ";
cin >> alpha;
int size;
if(alpha >= 'A' && alpha <= 'Z') {
size = (alpha-'A')+1;
} else if(alpha >= 'a' && alpha <= 'z') {
size = (alpha-'a') + 1;
}
char* ptr1 = new char[size];

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 10 of 3


Pointer Arrays & Pointers to Structures LAB 06

char* ptr2 = new char[size];


int a = 0, b = 0;
for (char ch = alpha; ch <= 'z' && ch >= alpha; ch++) {
*(ptr1 + a++) = ch;
}
if (alpha >= 'A' && alpha <= 'Z') {
for (char ch = alpha; ch >= 'A'; ch--) {
*(ptr2 + b++) = ch;
}
} else {
for (char ch = alpha; ch >= 'a'; ch--) {
*(ptr2 + b++) = ch;
}
}
cout << "Array 1: ";
for (int i = 0; i < size; i++) {
cout << *(ptr1 + i) << " ";
if(*(ptr1+i)=='z' || *(ptr1+i)=='Z') {
break;
}
}
cout << endl;
cout << "Array 2: ";
for (int i = 0; i < size; i++) {
cout << *(ptr2 + i) << " ";
if(*(ptr2+i)=='a' || *(ptr2+i)=='A') {
break;
}
}
cout << endl;
delete[] ptr1;
delete[] ptr2;
return 0;
}

OUTPUT:

Spring 2023 OOP Lab NUCES, ISLAMABAD Page 11 of 3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy