SlideShare a Scribd company logo
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
Most read
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
Most read
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.
Most read
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?

More Related Content

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

Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
Koganti Ravikumar
 
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
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
Pointer
PointerPointer
Pointer
Fahuda E
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
Pointers
PointersPointers
Pointers
Prof. Dr. K. Adisesha
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
Mauryasuraj98
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
HimanshuSharma997566
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
Programming in Computer Science- Pointers in C++.ppt
Programming in Computer Science- Pointers in C++.pptProgramming in Computer Science- Pointers in C++.ppt
Programming in Computer Science- Pointers in C++.ppt
richardbaahnkansah
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
Sabaunnisa3
 
Pointers
PointersPointers
Pointers
Frijo Francis
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
pointer.pptx module of information technology
pointer.pptx module of information technologypointer.pptx module of information technology
pointer.pptx module of information technology
jolynetomas
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
lodhran-hayat
 
P1
P1P1
P1
Hitesh Wagle
 
Pointers
PointersPointers
Pointers
Hitesh Wagle
 
c++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptxc++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptx
fn723290
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
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
 
Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]Pf cs102 programming-9 [pointers]
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
arraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptxarraytypes of array and pointer string in c++.pptx
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
Programming in Computer Science- Pointers in C++.ppt
Programming in Computer Science- Pointers in C++.pptProgramming in Computer Science- Pointers in C++.ppt
Programming in Computer Science- Pointers in C++.ppt
richardbaahnkansah
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
pointer.pptx module of information technology
pointer.pptx module of information technologypointer.pptx module of information technology
pointer.pptx module of information technology
jolynetomas
 
Arrry structure Stacks in data structure
Arrry structure Stacks  in data structureArrry structure Stacks  in data structure
Arrry structure Stacks in data structure
lodhran-hayat
 
c++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptxc++ introduction, array, pointers included.pptx
c++ introduction, array, pointers included.pptx
fn723290
 

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)

Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
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