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

Lecture 2 OOP Spring 2025

The document covers various concepts related to pointers in programming, including pass by value/reference, pointer arithmetic, and memory allocation. It provides examples of valid and invalid pointer operations, discusses the differences between pointers and references, and explains the use of constant pointers. Additionally, it addresses returning pointers from functions and includes tasks for practical application of the concepts.
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)
4 views

Lecture 2 OOP Spring 2025

The document covers various concepts related to pointers in programming, including pass by value/reference, pointer arithmetic, and memory allocation. It provides examples of valid and invalid pointer operations, discusses the differences between pointers and references, and explains the use of constant pointers. Additionally, it addresses returning pointers from functions and includes tasks for practical application of the concepts.
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/ 24

Pointers

Contents:
• Pass by Value/References
• Pointers as Parameter
• Constant Pointers Lecture 2
Usman Anwer
Lecturer

Spring-2025
Task
Assume pint is a pointer variable. Is each of the following statements valid or
invalid? If any is invalid, why?

A) pint++;
B) −−pint;
C) pint /= 2;
D) pint *= 4;
E) pint += x; // Assume x is an int.
Which one is Valid?

int ages[20];
int *pint = ages;
OR
float myFloat;
int *pint = &myFloat;
Comparing Pointers

if (&arr[1] > &arr[0])


if (arr < &arr[4])
if (arr == &arr[0])
if (&arr[2] != &arr[3])

Which of the above statement is invalid?


Program
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums = set; // Make nums point to set
cout << "The numbers in set are:\n";
cout << *nums << " "; // Display first element
while (nums < &set[7]) {
nums++;
cout << *nums << " "; }
Pass by Value/Reference

● In pass by value, a copy of the variable is passed to the function. Any


changes made to the parameter inside the function do not affect the original
variable.
● In pass by reference, the address (or reference) of the variable is passed
to the function. Any changes made to the parameter inside the function
directly affect the original variable.
● Arrays are passed as reference automatically during a function call.
Pass by Reference/Value

void modifyValue(int &num) {


num = 20;
}
Main Function

int main()
{
int a = 10;
modifyValue(a);
cout << "Value of a after function call: " << a << endl;
return 0;
}
Array as an Argument
void sum(int array[], int size) {
for (int i = 0;i < size;i++) {
array[i] = array[i] + 5;
} }

const int size = 5;


int arr[size] = { 1,2,3,4,5 };
sum(arr, size);
cout << "After function call " << endl; Output= ?
for (int i = 0;i < size;i++) {
cout << arr[i] << " ";}
Array as an Argument Reference Variables
void sum(int array[], int size) {
for (int i = 0;i < size;i++) {
array[i] = array[i] + 5;
} }
Output=
const int size = 5; After function call
int arr[size] = { 1,2,3,4,5 }; 6 7 8 9 10
sum(arr, size);
cout << "After function call " << endl;
for (int i = 0;i < size;i++) { > array works as a pointer
cout << arr[i] << " ";} > Pointers is a simplified
way to manage references
Pointers as Function Parameters
● Reference variables are much easier to work with than pointers.
● References hide all the “mechanics” of dereferencing and indirection.

void doubleValue(int *val)


{
*val *= 2;
}
doubleValue(&number);
Pointers as Function Parameters
Taking input from user and store the value in pointer:

void getNumber(int *input) {

cout << "Enter an integer number: ";

cin >> *input; //what's wrong with cin>>input?

}
Pointers as Function Parameters

void getSales(double *arr, int size){

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

cout << "Enter the sales figure for quarter ";

cout << (count + 1) << ": ";


main():
cin >> arr[count]; const int QTRS = 4;
double sales[QTRS];
}} getSales(sales, QTRS);
Pointers as Function Parameters

double totalSales(double *arr, int size) {

double sum = 0.0;

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

sum += *arr;
main():
arr++; const int QTRS = 4;
double sales[QTRS];
} return sum; } getSales(sales, QTRS);
totalSales(sales, QTRS)

sum += *arr++;?
Pointer to Constants
Example 1:
const int val = 23; // Constant variable
const int* ptr=&val; // Pointer to constant variable
*ptr = *ptr * 2; //ERROR; Cannot be modified

Example 2:
int abc = 23; // Integer variable
const int* ptr1=&abc; //Constant pointer to non-constant variable
*ptr1 = *ptr1 * 2; // ERROR; Cannot be modified
Pointer to Constants
Example 3:
const int val = 23; // Constant variable
int* ptr=&val; // ERROR! Pointer to constant variable

Summary is:
• Constant pointer can hold reference of constant variable.
• Constant pointer can also hold the reference of non-constant
variable.
• Non-Constant pointer cannot hold the reference of constant variable.
• Pointers to constant variables can change its reference.
Constant Pointers
Constant pointers refer to pointers that cannot change the address
they are pointing to after initialization but value can be changed.

int a = 10, b = 20;


int * const ptr = &a; // Constant pointer to an int
*ptr = 20; // Valid: Modifying the value at the address
ptr = &b; // Error: Cannot change the address it points to
Constant Pointer to a Constant
Constant pointers refer to pointers that cannot change the address
they are pointing to after initialization but value can be changed.

int a = 10, b = 20;


const int * const ptr = &a; // Constant pointer to an int
*ptr = 20; // Error: Cannot modify the value at the address
ptr = &b; // Error: Cannot change the address it points to
Returning Pointers From Functions
• Returning a pointer to a local variable is invalid because the local
variable will go out of scope once the function exits, leading to
undefined behavior.

int* invalidFunction() {
int x = 10; // Local variable
return &x; // Returning address of a local variable
}
Memory Allocations to Pointers

new operator is used to allocate memory to a pointer

Example 1: Allocating memory to an Integer


int *iptr = nullptr; //declares a null pointer
iptr = new int; // dynamically allocates 4 bytes to pointer
delete iptr //deallocates the memory
Memory Allocations to Pointers

new operator is used to allocate memory to a pointer

Example 2: Allocating memory to an array


const int SIZE = 100;
int *iptr = new int[SIZE]; // Allocate space for a 100-element
delete [] iptr; // Deallocates the memory
Returning Pointers from Functions
• You can safely return a pointer to dynamically allocated memory
using new. The memory remains valid until explicitly deallocated with
delete.

int* allocateMemory() {
int* ptr = new int(42); // Dynamically allocate memory
return ptr;
}
Questions
• Difference between:
const int* ptr
int* const ptr
const int* const ptr
• What happens if you return a pointer to an automatic (local) variable
from a function?
• Difference between a pointer and a reference?
Pointer vs Reference
Class Task
Write a function that performs pointer arithmetic to
reverse an array in place. The function should not
use array indexing (arr[1])?

* You are not allowed to create new array

You might also like