SlideShare a Scribd company logo
1
Pointers in C++
Ahmad Baryal
Saba Institute of Higher Education
Computer Science Faculty
Nov 18, 2024
2 Table of contents
 Introduction to pointers
 How to use pointers
 References and Pointers
 Array Name as Pointers
 Pointer Expressions and Pointer Arithmetic
 Advanced Pointer Notations
 Pointers and String literals
 Pointers to pointers
 Void Pointers, Invalid Pointers and NULL Pointers
 Advantage of pointer
3 C++ Pointers
• The pointer in C++ language is a variable, it is also known as locator or indicator that
points to an address of a value.
• The symbol of an address is represented by a pointer. In addition to creating and
modifying dynamic data structures, they allow programs to emulate call-by-
reference. One of the principal applications of pointers is iterating through the
components of arrays or other data structures.
• The pointer variable that refers to the same datatype as the variable you're dealing
with, has the address of that variable set to it (such as an int or string).
Syntax
1.datatype *var_name;
2.int *ptr; // ptr can point to an address which holds int dat
a
4 How to use a pointer?
1. Establish a pointer variable.
2. employing the unary operator (&), which yields the address of the variable, to assign a
pointer to a variable's address.
3. Using the unary operator (*), which gives the variable's value at the address provided
by its argument, one can access the value stored in an address.
Since the data type knows how many bytes the information is held in, we associate it with
a reference. The size of the data type to which a pointer points is added when we
increment a pointer.
5 Usage of pointer
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In C++ language, we can dynamically allocate memory using malloc() and calloc() functions
where pointer is used.
2) Arrays, Functions and Structures
Pointers in C++ language are widely used in arrays, functions and structures. It reduces
the code and improves the performance.
6 Symbols used in pointer
7 Declaring a pointer
The pointer in C++ language can be declared using (asterisk symbol).
∗
int a; //pointer to int
∗
char c; //pointer to char
∗
Pointer Example: Let's see the simple example of using pointers printing the address and value.
#include <iostream>
using namespace std;
int main()
{
int number=30;
int p;
∗
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
8 Array Name as Pointers
An array name contains the address of the first element of the array which acts like a constant
pointer. It means, the address stored in the array name can’t be changed. For example, if we
have an array named val then val and &val[0] can be used interchangeably.
void geeks()
{
// Declare an array
int val[3] = { 5, 10, 20 };
// declare pointer variable
int* ptr;
// Assign the address of val[0] to ptr
// We can use ptr=&val[0];(both are same)
ptr = val;
cout << "Elements of the array are: ";
cout << ptr[0] << " " << ptr[1] << " " << ptr[2];
}
// Driver program
int main() { geeks(); }
9 Pointer Expressions and Pointer Arithmetic
A limited set of arithmetic operations can be performed on pointers which are:
• incremented ( ++ )
• decremented ( — )
• an integer may be added to a pointer ( + or += )
• an integer may be subtracted from a pointer ( – or -= )
• difference between two pointers (p1-p2)
10 Example
void geeks()
{
int v[3] = { 10, 100, 200 };
int* ptr;
// Assign the address of v[0] to ptr
ptr = v;
for (int i = 0; i < 3; i++) {
cout << "Value at ptr = " << ptr << "n";
cout << "Value at *ptr = " << *ptr << "n";
// Increment pointer ptr by 1
ptr++;
}
}
int main() { geeks(); }
Value at ptr = 0x7ffe5a2d8060
Value at *ptr = 10
Value at ptr = 0x7ffe5a2d8064
Value at *ptr = 100
Value at ptr = 0x7ffe5a2d8068
Value at *ptr = 200
Output:
11 References and Pointers
There are 3 ways to pass C++ arguments to a function:
• Call-By-Value
• Call-By-Reference with a Pointer Argument
• Call-By-Reference with a Reference Argument
• In C++, function arguments can be passed in different ways, providing flexibility in how data
is accessed and modified within functions. Two common methods are using references and
pointers. This section explores three ways to pass arguments to a function: Call-By-Value,
Call-By-Reference with a Pointer Argument, and Call-By-Reference with a Reference
Argument.
12 References and Pointers
1. Call-By-Value in C++ Function Arguments
In C++, Call-By-Value is a method of passing function arguments where the actual value of the
variable is copied into the function parameter. This example illustrates how modifications inside
the function do not affect the original value.
#include <iostream>
using namespace std;
// Function prototype
void squareByValue(int x);
int main() {
int number = 5;
cout << "Original value: " << number << endl;
// Calling the function with a value
squareByValue(number);
cout << "Value after function call: " << number << endl;
return 0;
}
// Function definition
void squareByValue(int x) {
x = x * x;
cout << "Value inside function: " << x << endl;
}
13 References and Pointers
2. Call-By-Reference with a Pointer Argument in C++ Function Arguments
Call-By-Reference with a Pointer Argument in C++ allows a function to modify the original value
by passing the address of the variable. This example demonstrates how changes made inside
the function affect the original value through a pointer.
#include <iostream>
using namespace std;
// Function prototype
void squareByReference(int *ptr);
int main() {
int number = 5;
cout << "Original value: " << number << endl;
// Calling the function with a pointer to the variable
squareByReference(&number);
cout << "Value after function call: " << number << endl;
return 0;
}
// Function definition
void squareByReference(int *ptr) {
*ptr = (*ptr) * (*ptr);
cout << "Value inside function: " << *ptr << endl;
}
14 References and Pointers
3. Call-By-Reference with a Reference Argument in C++ Function Arguments
Call-By-Reference with a Reference Argument in C++ provides a cleaner syntax than using
pointers. This example demonstrates how changes made inside the function directly affect the
original variable.
#include <iostream>
using namespace std;
// Function prototype
void squareByReference(int &ref);
int main() {
int number = 5;
cout << "Original value: " << number << endl;
// Calling the function with a reference to the variable
squareByReference(number);
cout << "Value after function call: " << number << endl;
return 0;
}
// Function definition
void squareByReference(int &ref) {
ref = ref * ref;
cout << "Value inside function: " << ref << endl;
}
15 Advanced Pointer Notation
Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration.
int nums[2][3] = { { 16, 18, 20 }, { 25, 26, 27 } };
In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j)
1. Using Array Notation:
nums[i][j] accesses the element at the ith row and jth column of the array.
2. Using Pointer Notation:
 *(*(nums + i) + j) is an equivalent expression using pointer notation. It can be interpreted as follows:
• nums + i: This gives the address of the ith row.
• *(nums + i): Dereferencing this gives the array at the ith row.
• *(nums + i) + j: This gives the address of the jth element in the ith row.
• *(*(nums + i) + j): Finally, this dereferences that address to get the value at the ith row and jth column.
16 Advanced Pointer Notation Example
In this C++ example, a two-dimensional array named nums is declared and initialized with integer
values. The program demonstrates two ways to access a specific element in this array:
Array Notation:
The syntax nums[i][j] is used, where i represents the row index, and j represents the column index. This
is a standard way of accessing elements in a two-dimensional array.
Pointer Notation:
The equivalent expression *(*(nums + i) + j) is used. This involves pointer arithmetic where nums + i
gives the address of the ith row, *(nums + i) dereferences that address, and *(nums + i) + j gives the
address of the jth element in the ith row. Finally, *(*(nums + i) + j) dereferences that address to
obtain the value.
Output:
Array Notation: 27
Pointer Notation: 27
17 Pointers and String literals
String literals are arrays containing null-terminated character sequences. String literals
are arrays of type character plus terminating null-character, with each of the elements
being of type const char (as characters of string can’t be modified).
const char* ptr = "geek";
This declares an array with the literal representation for “geek”, and then a pointer to its
first element is assigned to ptr. If we imagine that “geek” is stored at the memory
locations that start at address 1800, we can represent the previous declaration as:
As pointers and arrays behave in the same way in
expressions, ptr can be used to access the characters of a
string literal. For example:
char x = *(ptr+3);
char y = ptr[3];
Here, both x and y contain k stored at 1803 (1800+3).
18 Pointers to pointers
In C++, we can create a pointer to a pointer that in turn may point to data or
another pointer. The syntax simply requires the unary operator (*) for each
level of indirection while declaring the pointer.
char a;
char *b;
char **c;
a = 'g'; // Assign the character 'g' to variable a
b = &a; // b is a pointer that points to the address of a
c = &b; // c is a pointer to a pointer, and it points to the address of b
Here b points to a char that stores ‘g’ and c points to the pointer b.
19 Void Pointers
• This is a special type of pointer available in C++ which represents the
absence of type.
• Void pointers are pointers that point to a value that has no type (and thus
also an undetermined length and undetermined dereferencing
properties). This means that void pointers have great flexibility as they can
point to any data type. There is a payoff for this flexibility.
• These pointers cannot be directly dereferenced. They have to be first
transformed into some other pointer type that points to a concrete data
type before being dereferenced.
20 Invalid pointers
• A pointer should point to a valid address but not necessarily to valid
elements (like for arrays). These are called invalid pointers. Uninitialized
pointers are also invalid pointers.
int *ptr1;
int arr[10];
int *ptr2 = arr+20;
Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of
bounds of arr so it also becomes an invalid pointer. (Note: invalid pointers do
not necessarily raise compile errors)
21 NULL Pointers & Advantages of Array
A null pointer is a pointer that point nowhere and not just an invalid address.
Following are 2 methods to assign a pointer as NULL;
int *ptr1 = 0;
int *ptr2 = NULL;
Advantages of Pointers:
• Pointers reduce the code and improve performance. They are used to
retrieve strings, trees, arrays, structures, and functions.
• Pointers allow us to return multiple values from functions.
• In addition to this, pointers allow us to access a memory location in the
computer’s memory.
22
Any Question?
Ad

More Related Content

Similar to Pointers in C++ object oriented programming (20)

Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
SwapnaliPawar27
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
ShashiShash2
 
chapter-11-pointers.pdf
chapter-11-pointers.pdfchapter-11-pointers.pdf
chapter-11-pointers.pdf
study material
 
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
Pointer in C++_Somesh_Kumar_Dewangan_SSTCPointer in C++_Somesh_Kumar_Dewangan_SSTC
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
drsomeshdewangan
 
Pointers.pdf
Pointers.pdfPointers.pdf
Pointers.pdf
clashontitanth11
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
Pointers
PointersPointers
Pointers
Vardhil Patel
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
20.C++Pointer.pptx
20.C++Pointer.pptx20.C++Pointer.pptx
20.C++Pointer.pptx
AtharvPotdar2
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
aarockiaabinsAPIICSE
 
chapter03.ppt easy words to understand and
chapter03.ppt easy words to understand andchapter03.ppt easy words to understand and
chapter03.ppt easy words to understand and
RehaanZaina1
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Monishkanungo
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
hozaifafadl
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
sudhakargeruganti
 
13092119343434343432232323121211213435554
1309211934343434343223232312121121343555413092119343434343432232323121211213435554
13092119343434343432232323121211213435554
simplyamrita2011
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
Mauryasuraj98
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
ShashiShash2
 
chapter-11-pointers.pdf
chapter-11-pointers.pdfchapter-11-pointers.pdf
chapter-11-pointers.pdf
study material
 
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
Pointer in C++_Somesh_Kumar_Dewangan_SSTCPointer in C++_Somesh_Kumar_Dewangan_SSTC
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
drsomeshdewangan
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Meghaj Mallick
 
chapter03.ppt easy words to understand and
chapter03.ppt easy words to understand andchapter03.ppt easy words to understand and
chapter03.ppt easy words to understand and
RehaanZaina1
 
Programming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explainedProgramming fundamentals 2:pointers in c++ clearly explained
Programming fundamentals 2:pointers in c++ clearly explained
hozaifafadl
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
sudhakargeruganti
 
13092119343434343432232323121211213435554
1309211934343434343223232312121121343555413092119343434343432232323121211213435554
13092119343434343432232323121211213435554
simplyamrita2011
 

More from Ahmad177077 (12)

Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Operators in c++ programming types of variablesOperators in c++ programming types of variables
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Introduction to c++ programming languageIntroduction to c++ programming language
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts AlgorithmsSelection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithmStrassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementationRecursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Graph Theory in Theoretical computer scienceGraph Theory in Theoretical computer science
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer sciencePropositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer ScienceProof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
1. Introduction to C++ and brief history1. Introduction to C++ and brief history
1. Introduction to C++ and brief history
Ahmad177077
 
Array In C++ programming object oriented programming
Array In C++ programming object oriented programmingArray In C++ programming object oriented programming
Array In C++ programming object oriented programming
Ahmad177077
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Operators in c++ programming types of variables
Operators in c++ programming types of variablesOperators in c++ programming types of variables
Operators in c++ programming types of variables
Ahmad177077
 
2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx2. Variables and Data Types in C++ proramming.pptx
2. Variables and Data Types in C++ proramming.pptx
Ahmad177077
 
Introduction to c++ programming language
Introduction to c++ programming languageIntroduction to c++ programming language
Introduction to c++ programming language
Ahmad177077
 
Selection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts AlgorithmsSelection Sort & Insertion Sorts Algorithms
Selection Sort & Insertion Sorts Algorithms
Ahmad177077
 
Strassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithmStrassen's Matrix Multiplication divide and conquere algorithm
Strassen's Matrix Multiplication divide and conquere algorithm
Ahmad177077
 
Recursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementationRecursive Algorithms with their types and implementation
Recursive Algorithms with their types and implementation
Ahmad177077
 
Graph Theory in Theoretical computer science
Graph Theory in Theoretical computer scienceGraph Theory in Theoretical computer science
Graph Theory in Theoretical computer science
Ahmad177077
 
Propositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer sciencePropositional Logics in Theoretical computer science
Propositional Logics in Theoretical computer science
Ahmad177077
 
Proof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer ScienceProof Techniques in Theoretical computer Science
Proof Techniques in Theoretical computer Science
Ahmad177077
 
1. Introduction to C++ and brief history
1. Introduction to C++ and brief history1. Introduction to C++ and brief history
1. Introduction to C++ and brief history
Ahmad177077
 
Ad

Recently uploaded (20)

Build 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHSBuild 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHS
TECH EHS Solution
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Build 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHSBuild 3D Animated Safety Induction - Tech EHS
Build 3D Animated Safety Induction - Tech EHS
TECH EHS Solution
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Mastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdfMastering Advance Window Functions in SQL.pdf
Mastering Advance Window Functions in SQL.pdf
Spiral Mantra
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Social Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTechSocial Media App Development Company-EmizenTech
Social Media App Development Company-EmizenTech
Steve Jonas
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Ad

Pointers in C++ object oriented programming

  • 1. 1 Pointers in C++ Ahmad Baryal Saba Institute of Higher Education Computer Science Faculty Nov 18, 2024
  • 2. 2 Table of contents  Introduction to pointers  How to use pointers  References and Pointers  Array Name as Pointers  Pointer Expressions and Pointer Arithmetic  Advanced Pointer Notations  Pointers and String literals  Pointers to pointers  Void Pointers, Invalid Pointers and NULL Pointers  Advantage of pointer
  • 3. 3 C++ Pointers • The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. • The symbol of an address is represented by a pointer. In addition to creating and modifying dynamic data structures, they allow programs to emulate call-by- reference. One of the principal applications of pointers is iterating through the components of arrays or other data structures. • The pointer variable that refers to the same datatype as the variable you're dealing with, has the address of that variable set to it (such as an int or string). Syntax 1.datatype *var_name; 2.int *ptr; // ptr can point to an address which holds int dat a
  • 4. 4 How to use a pointer? 1. Establish a pointer variable. 2. employing the unary operator (&), which yields the address of the variable, to assign a pointer to a variable's address. 3. Using the unary operator (*), which gives the variable's value at the address provided by its argument, one can access the value stored in an address. Since the data type knows how many bytes the information is held in, we associate it with a reference. The size of the data type to which a pointer points is added when we increment a pointer.
  • 5. 5 Usage of pointer There are many usage of pointers in C++ language. 1) Dynamic memory allocation In C++ language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used. 2) Arrays, Functions and Structures Pointers in C++ language are widely used in arrays, functions and structures. It reduces the code and improves the performance.
  • 6. 6 Symbols used in pointer
  • 7. 7 Declaring a pointer The pointer in C++ language can be declared using (asterisk symbol). ∗ int a; //pointer to int ∗ char c; //pointer to char ∗ Pointer Example: Let's see the simple example of using pointers printing the address and value. #include <iostream> using namespace std; int main() { int number=30; int p; ∗ p=&number;//stores the address of number variable cout<<"Address of number variable is:"<<&number<<endl; cout<<"Address of p variable is:"<<p<<endl; cout<<"Value of p variable is:"<<*p<<endl; return 0; }
  • 8. 8 Array Name as Pointers An array name contains the address of the first element of the array which acts like a constant pointer. It means, the address stored in the array name can’t be changed. For example, if we have an array named val then val and &val[0] can be used interchangeably. void geeks() { // Declare an array int val[3] = { 5, 10, 20 }; // declare pointer variable int* ptr; // Assign the address of val[0] to ptr // We can use ptr=&val[0];(both are same) ptr = val; cout << "Elements of the array are: "; cout << ptr[0] << " " << ptr[1] << " " << ptr[2]; } // Driver program int main() { geeks(); }
  • 9. 9 Pointer Expressions and Pointer Arithmetic A limited set of arithmetic operations can be performed on pointers which are: • incremented ( ++ ) • decremented ( — ) • an integer may be added to a pointer ( + or += ) • an integer may be subtracted from a pointer ( – or -= ) • difference between two pointers (p1-p2)
  • 10. 10 Example void geeks() { int v[3] = { 10, 100, 200 }; int* ptr; // Assign the address of v[0] to ptr ptr = v; for (int i = 0; i < 3; i++) { cout << "Value at ptr = " << ptr << "n"; cout << "Value at *ptr = " << *ptr << "n"; // Increment pointer ptr by 1 ptr++; } } int main() { geeks(); } Value at ptr = 0x7ffe5a2d8060 Value at *ptr = 10 Value at ptr = 0x7ffe5a2d8064 Value at *ptr = 100 Value at ptr = 0x7ffe5a2d8068 Value at *ptr = 200 Output:
  • 11. 11 References and Pointers There are 3 ways to pass C++ arguments to a function: • Call-By-Value • Call-By-Reference with a Pointer Argument • Call-By-Reference with a Reference Argument • In C++, function arguments can be passed in different ways, providing flexibility in how data is accessed and modified within functions. Two common methods are using references and pointers. This section explores three ways to pass arguments to a function: Call-By-Value, Call-By-Reference with a Pointer Argument, and Call-By-Reference with a Reference Argument.
  • 12. 12 References and Pointers 1. Call-By-Value in C++ Function Arguments In C++, Call-By-Value is a method of passing function arguments where the actual value of the variable is copied into the function parameter. This example illustrates how modifications inside the function do not affect the original value. #include <iostream> using namespace std; // Function prototype void squareByValue(int x); int main() { int number = 5; cout << "Original value: " << number << endl; // Calling the function with a value squareByValue(number); cout << "Value after function call: " << number << endl; return 0; } // Function definition void squareByValue(int x) { x = x * x; cout << "Value inside function: " << x << endl; }
  • 13. 13 References and Pointers 2. Call-By-Reference with a Pointer Argument in C++ Function Arguments Call-By-Reference with a Pointer Argument in C++ allows a function to modify the original value by passing the address of the variable. This example demonstrates how changes made inside the function affect the original value through a pointer. #include <iostream> using namespace std; // Function prototype void squareByReference(int *ptr); int main() { int number = 5; cout << "Original value: " << number << endl; // Calling the function with a pointer to the variable squareByReference(&number); cout << "Value after function call: " << number << endl; return 0; } // Function definition void squareByReference(int *ptr) { *ptr = (*ptr) * (*ptr); cout << "Value inside function: " << *ptr << endl; }
  • 14. 14 References and Pointers 3. Call-By-Reference with a Reference Argument in C++ Function Arguments Call-By-Reference with a Reference Argument in C++ provides a cleaner syntax than using pointers. This example demonstrates how changes made inside the function directly affect the original variable. #include <iostream> using namespace std; // Function prototype void squareByReference(int &ref); int main() { int number = 5; cout << "Original value: " << number << endl; // Calling the function with a reference to the variable squareByReference(number); cout << "Value after function call: " << number << endl; return 0; } // Function definition void squareByReference(int &ref) { ref = ref * ref; cout << "Value inside function: " << ref << endl; }
  • 15. 15 Advanced Pointer Notation Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration. int nums[2][3] = { { 16, 18, 20 }, { 25, 26, 27 } }; In general, nums[ i ][ j ] is equivalent to *(*(nums+i)+j) 1. Using Array Notation: nums[i][j] accesses the element at the ith row and jth column of the array. 2. Using Pointer Notation:  *(*(nums + i) + j) is an equivalent expression using pointer notation. It can be interpreted as follows: • nums + i: This gives the address of the ith row. • *(nums + i): Dereferencing this gives the array at the ith row. • *(nums + i) + j: This gives the address of the jth element in the ith row. • *(*(nums + i) + j): Finally, this dereferences that address to get the value at the ith row and jth column.
  • 16. 16 Advanced Pointer Notation Example In this C++ example, a two-dimensional array named nums is declared and initialized with integer values. The program demonstrates two ways to access a specific element in this array: Array Notation: The syntax nums[i][j] is used, where i represents the row index, and j represents the column index. This is a standard way of accessing elements in a two-dimensional array. Pointer Notation: The equivalent expression *(*(nums + i) + j) is used. This involves pointer arithmetic where nums + i gives the address of the ith row, *(nums + i) dereferences that address, and *(nums + i) + j gives the address of the jth element in the ith row. Finally, *(*(nums + i) + j) dereferences that address to obtain the value. Output: Array Notation: 27 Pointer Notation: 27
  • 17. 17 Pointers and String literals String literals are arrays containing null-terminated character sequences. String literals are arrays of type character plus terminating null-character, with each of the elements being of type const char (as characters of string can’t be modified). const char* ptr = "geek"; This declares an array with the literal representation for “geek”, and then a pointer to its first element is assigned to ptr. If we imagine that “geek” is stored at the memory locations that start at address 1800, we can represent the previous declaration as: As pointers and arrays behave in the same way in expressions, ptr can be used to access the characters of a string literal. For example: char x = *(ptr+3); char y = ptr[3]; Here, both x and y contain k stored at 1803 (1800+3).
  • 18. 18 Pointers to pointers In C++, we can create a pointer to a pointer that in turn may point to data or another pointer. The syntax simply requires the unary operator (*) for each level of indirection while declaring the pointer. char a; char *b; char **c; a = 'g'; // Assign the character 'g' to variable a b = &a; // b is a pointer that points to the address of a c = &b; // c is a pointer to a pointer, and it points to the address of b Here b points to a char that stores ‘g’ and c points to the pointer b.
  • 19. 19 Void Pointers • This is a special type of pointer available in C++ which represents the absence of type. • Void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereferencing properties). This means that void pointers have great flexibility as they can point to any data type. There is a payoff for this flexibility. • These pointers cannot be directly dereferenced. They have to be first transformed into some other pointer type that points to a concrete data type before being dereferenced.
  • 20. 20 Invalid pointers • A pointer should point to a valid address but not necessarily to valid elements (like for arrays). These are called invalid pointers. Uninitialized pointers are also invalid pointers. int *ptr1; int arr[10]; int *ptr2 = arr+20; Here, ptr1 is uninitialized so it becomes an invalid pointer and ptr2 is out of bounds of arr so it also becomes an invalid pointer. (Note: invalid pointers do not necessarily raise compile errors)
  • 21. 21 NULL Pointers & Advantages of Array A null pointer is a pointer that point nowhere and not just an invalid address. Following are 2 methods to assign a pointer as NULL; int *ptr1 = 0; int *ptr2 = NULL; Advantages of Pointers: • Pointers reduce the code and improve performance. They are used to retrieve strings, trees, arrays, structures, and functions. • Pointers allow us to return multiple values from functions. • In addition to this, pointers allow us to access a memory location in the computer’s memory.

Editor's Notes

  • #5: Malloc: memory allocation calloc: contigious allocation