0% found this document useful (0 votes)
0 views

Lab 02 - Pointers

The document provides an overview of pointers in C++, covering their definition, declaration, initialization, and manipulation. It explains pointer variables, dereferencing, pointer arithmetic, and their relationship with arrays. Additionally, it includes lab tasks for practical application, focusing on temperature analysis and grade management using pointers.

Uploaded by

Ubaid Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lab 02 - Pointers

The document provides an overview of pointers in C++, covering their definition, declaration, initialization, and manipulation. It explains pointer variables, dereferencing, pointer arithmetic, and their relationship with arrays. Additionally, it includes lab tasks for practical application, focusing on temperature analysis and grade management using pointers.

Uploaded by

Ubaid Ahmad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Lab 02: Pointers

Outcomes:
1. See the definition of a pointer.
2. Observe the basic pointer operators.
3. See mechanism for simple pointer manipulation.
4. Pointer to arrays

1.1 Background:
There are things and there are pointers to things (Figure 1).

Figure 1
Things can come in any size; some may be big, some may be small. Pointers
come in only one size (relatively small).*
Figure 1 shows one thing: a variable named thing. The name of the variable is
written on the box that represents it. This variable contains the value 6. The
actual address of this variable is 0x1000. C++ automatically assigns an address
to each variable at compile time. The actual addresses differ from machine to
machine.
The pointer (thing_ptr) points to the variable thing. Pointers are also called
address variables since they contain the addresses of other variables. In this
case, the pointer contains the address 0x1000. Since this is the address of thing,
you say that thing_ptr points to thing.

1.2 Pointer Variables:


A pointer is a variable that holds the address of a memory location. We know
that all the variables we declare, have a specific address in memory. We declare
a pointer variable to point to these addresses in memory.
A computer memory location has an address and holds a content. The address is
a numerical number (often expressed in hexadecimal), which is hard for
programmers to use directly. Typically, each address location holds 8-bit (i.e.,
1-byte) of data. It is entirely up to the programmer to interpret the meaning of
the data, such as integer, real number, characters or strings.
Each address location typically hold 8-bit (i.e., 1-byte) of data. A 4-byte int
value occupies 4 memory locations. A 32-bit system typically uses 32-bit
addresses. To store a 32-bit address, 4 memory locations are required.

The following diagram illustrate the relationship between computers' memory


address and content; and variable's name, type and value used by the
programmers.

Pointer variables contain memory addresses as their values. Normally, a


variable directly contains a specific value. A pointer contains the memory
address of a variable that, in turn, contains a specific value. In this sense, a
variable name directly references a value, and a pointer indirectly references a
value.
1.3 Declaring Pointers
Pointers, like any other variables, must be declared before they can be used.

The general syntax for declaring a pointer variable is:


datatype * variable_name;

For example:

This means countPtr is a pointer that points to a variable of type int. int * (i.e.,
a pointer to an int value) and is read (right to left), “countPtr is a pointer to
int.” Also, variable count is a simple just a variable, not a pointer to an int.
The * in the declaration applies only to countPtr. Each variable being declared
as a pointer must be preceded by an asterisk (*).

For example, the declaration:

indicates that both xPtr and yPtr are pointers to double values. When * appears
in a declaration, it isn’t an operator; rather, it indicates that the variable being
declared is a pointer.

Hence a pointer variable always contains a memory location or address. Let us


see the working of pointer variables below.
Consider we have the following declarations:
In memory, these declarations will be represented as follows:

This is the internal representation of pointer in memory. When we assign the


address variable to the pointer variable, it points to the variable as shown in the
representation above.

As ptr has an address of variable p, *ptr will give the value of variable p
(variable the pointer variable ptr is pointing to).

1.4 Initialization:
When you declare a pointer variable, its content is not initialized. In other words,
it contains an address of "somewhere", which is of course not a valid location.
This is dangerous! You need to initialize a pointer by assigning it a valid
address.

A pointer may be initialized to 0, NULL or an address of the corresponding


type.
A pointer with the value 0 or NULL points to nothing and is known as a null
pointer.

Symbolic constant NULL is defined in header file <iostream> to represent


the value 0. Initializing a pointer to NULL is equivalent to initializing a
pointer to 0,

To initialize the pointer with address of a variable, we need to use address-of


operator (&).
The address-of operator (&) operates on a variable, and returns the address of
the variable. For example, if thing_var is an int variable, &thing_var returns the
address of the variable thing_var.

You can use the address-of operator to get the address of a variable, and assign
the address to a pointer variable. For example,
int number = 88; // An int variable with a value

int * pNumber; // Declare a pointer variable called pNumber pointing to


an int (or
int pointer)
pNumber = &number; // Assign the address of the variable number to
pointer pNumber

int * pAnother = &number; // Declare another int pointer and init to address
of the variable number

1.5 Indirection or Dereferencing Operator (*)


The indirection operator (or dereferencing operator) (*) operates on a pointer,
and returns the value stored in the address kept in the pointer variable. For
example, if pNumber is an int pointer, *pNumber returns the int value "pointed
to" by pNumber.
For example,
int number = 88;
int * pNumber = &number; // Declare and assign the address of variable
number to pointer pNumber (0x22ccec)
cout << pNumber<< endl; // Print the content of the pointer variable, which
contain an address (0x22ccec)
cout << *pNumber << endl; // Print the value "pointed to" by the pointer,
which is an int (88)
*pNumber = 99; // Assign a value to where the pointer is pointed to,
NOT to the pointer variable
cout << *pNumber << endl; // Print the new value "pointed to" by the pointer
(99)
cout << number << endl; // The value of variable number changes as well
(99)

Take note that pNumber stores a memory address location, whereas *pNumber
refers to the value stored in the address kept in the pointer variable, or the value
pointed to by the pointer.

As illustrated, a variable (such as number) directly references a value, whereas a


pointer indirectly references a value through the memory address it stores.
Referencing a value indirectly via a pointer is called indirection or
dereferencing.

The indirection operator (*) can be used in both the RHS (temp = *pNumber)
and the LHS (*pNumber = 99) of an assignment statement.

Note that the symbol * has different meaning in a declaration statement


and in an expression. When it is used in a declaration (e.g., int * pNumber),
it denotes that the name followed is a pointer variable. Whereas when it is
used in a expression (e.g., *pNumber = 99; temp << *pNumber;), it refers
to the value pointed to by the pointer variable.
Example 1:
#include <iostream>
int main()
{
int thing_var; // Define a variable

int *thing_ptr; // Define a pointer

thing_var = 2; // Assigning a value to "thing"

cout << "Thing " << thing_var << '\n';

thing_ptr = &thing_var; // Make the pointer point to "thing"

*thing_ptr = 3; // thing_ptr points to thing_var so


// thing_var changes to 3

cout << "Thing " << thing_var << '\n';

// Another way of printing the data

cout << "Thing " << *thing_ptr << '\n';

return (0);
}
1.6 Pointer has a Type Too:
A pointer is associated with a type (of the value it points to), which is specified
during declaration. A pointer can only hold an address of the declared type; it
cannot hold an address of a different type.

Example:
int i = 88;
double d = 55.66;
int * iPtr = &i; // int pointer pointing to an int value
double * dPtr = &d; // double pointer pointing to a double value

iPtr = &d; // ERROR, cannot hold address of different type


dPtr = &i; // ERROR
iPtr = i; // ERROR, pointer holds address of an int, NOT int value

int j = 99;
iPtr = &j; // You can change the address stored in a pointer

1.7 Uninitialized Pointers:


The following code fragment has a serious logical error!

int * iPtr;
*iPtr = 55;
cout << *iPtr << endl;

The pointer iPtr was declared without initialization, i.e., it is pointing to


"somewhere" which is of course an invalid memory location. The *iPtr =
55 corrupts the value of "somewhere"! You need to initialize a pointer by
assigning it a valid address. Most of the compilers does not signal an error or a
warning for uninitialized pointer?!
1.8 Null Pointers:
You can initialize a pointer to 0 or NULL, i.e., it points to nothing. It is called
a null pointer. Dereferencing a null pointer (*p) causes
an STATUS_ACCESS_VIOLATION exception.
int * iPtr = 0; // Declare an int pointer, and initialize the pointer to point to
nothing
cout << *iPtr << endl; // ERROR! STATUS_ACCESS_VIOLATION
exception

int * p = NULL; // Also declare a NULL pointer points to nothing

Initialize a pointer to null during declaration is a good software engineering


practice.
1.9. Arrays and Pointers:
Arrays and pointers are strongly associated with one another. We know that the
name of the array points to the first element in the array and this is a constant
pointer.
We can assign this pointer to a pointer variable and then access the array either
by decrementing the pointer or by using the subscript operator.
We will see this association between the pointer variable and array in the
following code Example.
#include <iostream>
#include <string>
using namespace std;

int main()
{
int myarray[5] = {1, 1, 2, 3, 5};
int* ptrvar;
ptrvar = myarray;

for(int i=0;i<5;i++)
{
cout<<*ptrvar<<"\t";
ptrvar++;
}
return 0;}
Output: 1 1 2 3 5
In the above program, we assign the array name to a pointer variable. As the
array name points to the first element in the array, we can print the contents of
the entire array by using a pointer variable and increment it using the ++
operator. This is shown in the output.

1.10. Pointer Arithmetic


We know that a pointer variable always points to the address in memory.
Among the operations that we can perform, we have the following arithmetic
operations that are carried out on pointers.
 Increment operator (++)
 Decrement operator (–)
 Addition (+)
 Subtraction (-)
Let us see the usage of these operations in an Example program.
#include <iostream>
#include <string>
using namespace std;

int main()
{
int myarray[5] = {2, 4,6, 8,10};
int* myptr;
myptr = myarray;
cout<<"First element in the array :"<<*myptr<<endl;
myptr ++;
cout<<"next element in the array :"<<*myptr<<endl;
myptr +=1;
cout<<"next element in the array :"<<*myptr<<endl;
myptr--;
cout<<"next element in the array :"<<*myptr<<endl;
myptr -= 1;
cout<<"next element in the array :"<<*myptr<<endl;

return 0;
}
Output:

First element in the array :2


next element in the array :4
next element in the array :6
next element in the array :4
next element in the array :2

We have seen the arithmetic operations carried out on pointers. Note that the
increment operator ++ increments the pointer and points to the next element in
the array. Similarly, the decrement operator decrements the pointer variable by
1 so that it points to the previous element in the array.

We also use + and – operators. First, we have added 1 to the pointer variable.
The result shows that it points to the next element in the array. Similarly, –
operator makes the pointer variable to point to the previous element in the array.
LAB TASKS:

TASK # 1: Write the output of following codes.


Code Output

int var1 = 3;
int var2 = 24;
int var3 = 17;

cout << &var1 << endl;

cout << &var2 << endl;

cout << &var3 << endl;


}

int* pointVar, var;


var = 5;

pointVar = &var;

cout << *pointVar << endl;

int var = 5;
int* pointVar;
pointVar = &var;

cout << var << endl;

cout << &var << endl;

cout << pointVar << endl;

cout << *pointVar << endl;


int *ptr;
int arr[5];
ptr = &arr[1];
ptr2 = arr;

cout<<ptr2<<endl;
cout<<&arr<<endl;
cout << ptr << endl;
cout << ptr-- << endl;
cout << --ptr << endl;

void display (int *A)


{
cout<<*A<<endl;
cout<<*(A+1) <<endl;
*A=10;
}

int main ()
{
int arr[5]={1,2,3,4,5};
display(arr);
display(arr);
}

Task # 2:
A weather station records the temperature every hour for a day, resulting in 24 temperature
readings. These readings are stored in an array. Your task is to write a C program that uses
pointers to analyze this data.
 Store the 24 temperature readings in an array.
 Use pointers to iterate through the array and calculate the average temperature for the
day.
 Use pointers to find the highest and lowest temperatures recorded during the day.
 Print the average, maximum, and minimum temperatures.
Task # 3:
You are tasked with developing a program to manage and analyze grades for students in
multiple courses. Each course has a different number of students, and you need to
dynamically allocate memory for storing grades. The program should perform several
operations, including calculating averages, finding the highest and lowest grades, and sorting
the grades.
 Dynamically allocate memory to store grades for each course.
 Allow the user to input grades for each course.
 Calculate the average grade for each course.
 Determine the highest and lowest grades in each course.
 Sort the grades in ascending order for each course.
 Print the average, highest, lowest, and sorted grades for each course.
Lab # 02 Marks distribution
ER1 ER6 ER8
Task 3 points 3 points 4 points

Lab # 02 Rubric Evaluation Guideline:


# Qualities & 0 < Poor <= 1 1 < Satisfactory <= 2 2 < Excellent <=3
Criteria
ER1 Task Completion Minimal or no program Some tasks were completed, All tasks were completed,
functionality was but the program has errors or and the program runs
achieved. incomplete functionalities. without errors.
# Qualities & 0 < Poor <= 1 1 < Satisfactory <= 2 2 < Excellent <=3
Criteria
ER6 Program Output Output is inaccurate or Output is mostly accurate but Output is clear, accurate,
poorly presented. may lack labels, captions, or and well presented with
formatting. labels, captions, and proper
formatting.
# Qualities & 0 < Poor <= 1.5 1.5 < Satisfactory <= 3 3 < Excellent <= 4
Criteria
ER8 Question & Answers some questions Answers most questions Answers all questions
Answer but not confidently or confidently and based on lab confidently and
based on lab task task knowledge. demonstrates a deep
knowledge. understanding of the given
lab task.

You might also like