0% found this document useful (0 votes)
9 views12 pages

Lab Manual 12 - Pointers

The lab manual focuses on programming fundamentals, specifically pointers in C++. It includes objectives, definitions, examples, and tasks related to pointer declaration, dereferencing, and usage in functions. The manual also emphasizes the importance of pointers in memory manipulation and provides practical exercises for students to enhance their understanding.

Uploaded by

ridaajaz990
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)
9 views12 pages

Lab Manual 12 - Pointers

The lab manual focuses on programming fundamentals, specifically pointers in C++. It includes objectives, definitions, examples, and tasks related to pointer declaration, dereferencing, and usage in functions. The manual also emphasizes the importance of pointers in memory manipulation and provides practical exercises for students to enhance their understanding.

Uploaded by

ridaajaz990
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/ 12

Lab Manual: Programming Fundamentals

University of Management and Technology, Lahore


Campus

Lab- 12 Manual
Lab Instructor: Riaz Ahmad
Department of Computer Science
Email: [email protected]
Lab 1: Pointers
Lab Rubrics

Identify key programming


Areas Problem Understanding structures such as Design/ Development of Solutions
Assessed variables, loops, and
functions.
(CLO 1) (CLO 2) (CLO 3)
No able to identify key
Not able to understand Not able to Model a solution for a
Poor programming structures such
Problem given problem
as variables, loops, and
functions.

Partially able identify Modeled an average solution


Able to partially understand
Average key programming for a given problem using
the problem
structures such as programming principles
variables, loops, and
functions.

Thoroughly identify key


Modeled a proper solution for a
Very Good Fully Understand the problem programming structures
given problem using programming
such as variables, loops,
principles
and functions.

Department of Computer Science, UMT, Lahore. 1 Riaz Ahmad


Lab Manual: Programming Fundamentals

Objective(s):
To Understand about:
1. Able to use Pointers
2. Able to use pointers in function and structure.

Introduction
Pointers are powerful features of C++ that differentiates it from other
programming languages like Java and Python.
Pointers are used in C++ program to access the memory and manipulate the address.

What Are Pointers?


A pointer is a variable whose value is the address of another variable. Like any variable or
constant, you must declare a pointer before you can work with it. The general form of a pointer
variable declaration is:

type *var-name;

Here, type is the pointer's base type; it must be a valid C++ type and var-name is the name of
the pointer variable. The asterisk you used to declare a pointer is the same asterisk that you use
for multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer.

Following are the valid pointer declaration:

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.

Using Pointers in C++:


There are few important operations, which we will do with the pointers very frequently. a we define
a pointer variables b assign the address of a variable to a pointer and c finally access the value at
the address available in the pointer variable. This is done by using unary operator * that returns
the value of the variable located at the address specified by its operand. Following example makes use of
these operations:

Department of Computer Science, UMT, Lahore. 2 Riaz Ahmad


Lab Manual: Programming Fundamentals

#include <iostream>
using namespace std;
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}

When the above code is compiled and executed, it produces result something as follows:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Address in C++
To understand pointers, you should first know how data is stored on the computer.
Each variable you create in your program is assigned a location in the computer's
memory. The value the variable stores is actually stored in the location assigned. To
know where the data is stored, C++ has an & operator. The & (reference) operator
gives you the address occupied by a variable. If var is a variable then, &var gives the
address of that variable.

Department of Computer Science, UMT, Lahore. 3 Riaz Ahmad


Lab Manual: Programming Fundamentals

Example 1: Address in C++


#include <iostream>
using namespace std;

int main()
{
int var1 = 3;
int var2 = 24;
int var3 = 17;
cout << &var1 << endl;
cout << &var2 << endl;
cout << &var3 << endl;
}
Output

0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4

Note: You may not get the same result on your system.
The 0x in the beginning represents the address is in hexadecimal form.

Notice that first address differs from second by 4-bytes and second address differs
from third by 4-bytes.
This is because the size of integer (variable of type int) is 4 bytes in 64-bit system.

Pointers Variables
C++ gives you the power to manipulate the data in the computer's memory directly.
You can assign and de-assign any space in the memory as you wish. This is done
using Pointer variables.
Pointers variables are variables that points to a specific address in the memory
pointed by another variable.

int *p;
OR,
int* p;

How to declare a pointer?


The statement above defines a pointer variable p. It holds the memory address
The asterisk is a dereference operator which means pointer to.
Here, pointer p is a pointer to int, i.e., it is pointing to an integer value in the
memory address.

Department of Computer Science, UMT, Lahore. 4 Riaz Ahmad


Lab Manual: Programming Fundamentals

Reference operator (&) and Deference operator (*)


Reference operator (&) as discussed above gives the address of a variable.
To get the value stored in the memory address, we use the dereference operator (*).
For example: If a number variable is stored in the memory address 0x123, and it
contains a value 5.
The reference (&) operator gives the value 0x123, while the dereference (*) operator
gives the value 5.
Note: The (*) sign used in the declaration of C++ pointer is not the dereference
pointer. It is just a similar notation that creates a pointer.

Example 2: C++ Pointers

Example: C++ Program to demonstrate the working of pointer.


#include <iostream> using
namespace std; int main() {
int *pc, c;

c = 5;
cout << "Address of c (&c): " << &c << endl; cout << "Value of c
(c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c cout <<


"Address that pointer pc holds (pc): "<< pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11. cout <<
"Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

*pc = 2;
cout << "Address of c (&c): " << &c << endl; cout << "Value of c
(c): " << c << endl << endl;

return 0;
}

Department of Computer Science, UMT, Lahore. 5 Riaz Ahmad


Lab Manual: Programming Fundamentals

Output

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 2

Example:
#include <iostream>
using namespace std;
int main ()
{int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;}

Department of Computer Science, UMT, Lahore. 6 Riaz Ahmad


Lab Manual: Programming Fundamentals

Explanation of program
 When c = 5; the value 5 is stored in the address of variable c - 0x7fff5fbff8c.
 When pc = &c; the pointer pc holds the address of c - 0x7fff5fbff8c, and the expression (dereference
operator) *pc outputs the value stored in that address, 5.
 When c = 11; since the address pointer pc holds is the same as c - 0x7fff5fbff8c, change in the value of
c is also reflected when the expression *pc is executed, which now outputs 11.
 When *pc = 2; it changes the content of the address stored by pc - 0x7fff5fbff8c. This is changed from
11 to 2. So, when we print the value of c, the value is 2 as well.
Common mistakes when working with pointers
Suppose, you want pointer pc to point to the address of c. Then,

int c, *pc;
pc=c; /* Wrong! pc is address whereas, c is not an address. */
*pc=&c; /* Wrong! *pc is the value pointed by address whereas, %amp;c is an address.
*/ pc=&c; /* Correct! pc is an address and, %amp;pc is also an address. */
*pc=c; /* Correct! *pc is the value pointed by address and, c is also a value. */

Pointers and Functions


There are three ways to pass arguments to a function: by value, by reference, and by
pointer. If the function is intended to modify variables in the calling program, these
variables cannot be passed by value, since the function obtains only a copy of the
variable. However, either a reference argument or a pointer can be used in this
situation.

Department of Computer Science, UMT, Lahore. 7 Riaz Ahmad


Lab Manual: Programming Fundamentals

Passing Simple Variables


We’ll first review how arguments are passed by reference, and then compare
this to passing pointer arguments. The PASSREF program shows passing by
reference.
// arguments passed by reference
#include <iostream>
using namespace std;
void centimize(double& v)
{

v *= 2.54; //v is the same as var


}

int main()
{
void centimize(double&); //prototype double
var = 10.0; //var has value of 10 inches
cout << “var = “ << var << “ inches” << endl;
centimize(var); //change var to centimeters
cout << “var = “ << var << “ centimeters” << endl;
return 0;
}

Here we want to convert a variable var in main() from inches to centimeters. We pass the
variable by reference to the function centimize(). (Remember that the & following the data type
double in the prototype for this function indicates that the argument is passed by reference.)
The centimize() function multiplies the original variable by 2.54. Notice how the function refers
to the variable. It simply uses the argument name v; v and var are different names for the same
thing. Once it has converted var to centimeters, main() displays the result.

Department of Computer Science, UMT, Lahore. 8 Riaz Ahmad


Lab Manual: Programming Fundamentals

Here’s the output of PASSREF:

var = 10 inches var


= 25.4 centimeters

The next example, PASSPTR, shows an equivalent situation when pointers are used:
// passptr.cpp
// arguments passed by pointer
#include <iostream>
using namespace std;
void centimize(double* ptrd)
{
*ptrd *= 2.54; //*ptrd is the same as var
}

int main()
{
void centimize(double*); //prototype
double var = 10.0; //var has value of 10 inches
cout << “var = “ << var << “ inches” << endl;
centimize(&var); //change var to centimeters
cout << “var = “ << var << “ centimeters” << endl;
return 0;
}

The output of PASSPTR is the same as that of PASSREF.


The function centimize() is declared as taking an argument that is a pointer to double:

Department of Computer Science, UMT, Lahore. 9 Riaz Ahmad


Lab Manual: Programming Fundamentals

void centimize(double*) // argument is pointer to double


When main() calls the function, it supplies the address of the variable as the
argument: centimize(&var); Remember that this is not the variable itself, as it
is in passing by reference, but the variable’s address. Because the centimize()
function is passed an address, it must use the dereference operator, *ptrd, to
access the value stored at this address:
*ptrd *= 2.54; // multiply the contents of ptrd
by 2.54 Of course this is the same as
*ptrd = *ptrd * 2.54; // multiply the contents of ptrd by 2.54
where the standalone asterisk means multiplication. (This operator really gets
around.) Since ptrd contains the address of var, anything done to *ptrd is
actually done to var. Figure shows how changing *ptrd in the function changes
var in the calling program.

FIGURE

Passing a pointer as an argument to a function is in some ways similar to


passing a reference. They both permit the variable in the calling program to be
modified by the function. However, the mechanism is different. A reference is
an alias for the original variable, while a pointer is the address of the variable.

Department of Computer Science, UMT, Lahore. 10 Riaz Ahmad


Lab Manual: Programming Fundamentals

Tasks for Lab:


1. Pointer Declaration and Initialization:
 Declare a pointer to an integer and initialize it to point to an integer
variable. Print both the variable's value and the pointer's value
(address).
2. Pointer Dereferencing:
 Create a program that initializes an integer variable. Use a pointer
to change the variable’s value from the main function. Print the
original and modified values.
3. Function with Pointer Parameters:
 Write a function that takes a pointer as an argument and
increments the value it points to by 1. Call this function from main
and demonstrate that the original variable has changed.
4. Dynamic Memory Allocation:
 Create a program that dynamically allocates an array of integers
using new. Populate the array with values from 1 to 10 and print
the values. Finally, deallocate the memory using delete[].
5. Array Traversal Using Pointers:
 Write a program that initializes an array of 5 floating-point
numbers. Use a pointer to traverse and print the elements of the
array. Use pointer arithmetic to access elements.
6. Swapping Values Using Pointers:
 Implement a function that swaps two integer values using pointers.
In main, declare two integers, call the swap function, and print the
values before and after the swap.
7. Pointer to Pointer:
 Declare an integer variable and a pointer to that integer. Then,
declare another pointer that points to the first pointer. Print the
values at each level of indirection.
8. Const Pointers:
 Create a program that demonstrates the use of constant pointers
and pointers to constant values. Attempt to modify the value of the
pointed variable and observe the outcomes.
9. Dynamic 2D Array:
 Create a dynamic 2D array using pointers. Allocate memory for a
3x3 matrix, populate it with values, and then print the matrix.

Department of Computer Science, UMT, Lahore. 11 Riaz Ahmad


Lab Manual: Programming Fundamentals

Finally, deallocate the memory.


10.String Manipulation with Pointers:
 Write a program that uses a pointer to manipulate strings. For
example, write a function that counts the number of characters in a
string using pointer arithmetic.
11.Character Array to Pointer:
 Initialize a character array (string) and use a pointer to traverse and
print the characters one by one. Demonstrate how to stop when
reaching the null terminator.

Home Work:

Exercise 1 Write a program to declare 5 pointers and print their values.


Exercise 2 Write a program to demonstrate the pointers’ arithmetic.
Exercise 3 Write a program to implement basic mathematics (Add, Subtract, Multiply)
by using functions and pointers.
Exercise 4 Write a program to declare a pointer of 1D Array and print its addresses.
Exercise 5 Write a program to sort a 2D array (using pointers).
Exercise 6 A program to declare a pointer of 2D array and check its address is even or
odd (using functions).

Department of Computer Science, UMT, Lahore. 12 Riaz Ahmad

You might also like