SlideShare a Scribd company logo
Programming fundamentals 2
Chapter 3:Pointer
Miss:Hanan Hardam
1
Computer Skills2 for Scientific
Colleges
2
Pointers in C++
Topics to cover:
• Overview of Pointers
• Pointer Declaration
• Pointer Assignment
• Pointer Arithmetic
• Relations Between Pointers and Arrays
• Pointers and Strings
Computer Skills2 for Scientific
Colleges
3
Overview of Pointers
• A Pointer in C++ is variable whose value is a memory
address.
• With pointers many memory locations can be
referenced.
• Some data structures use pointers (e.g. linked list,
tree).
• The * and & operators
- & operator is the address operator
- * operator is the dereferencing operator. It is used in
pointers declaration
Computer Skills2 for Scientific
Colleges
4
Pointer Declaration
• Pointers are declared as follows:
<type> * variable_name ;
e.g.
int * xPtr; // xPtr is a pointer to data of type integer
char * cPtr; //cPtr is a pointer to data of type character
void * yPtr; // yPtr is a generic pointer,
// represents any type
Computer Skills2 for Scientific
Colleges
5
Pointer Assignment
• Assignment can be applied on pointers of the same type
• If not the same type, a cast operator must be used
• Exception: pointer to void does not need casting to convert a
pointer to void type
• void pointers cannot be dereferenced
• Example
int *xPtr, *yPtr; int x = 5;
…
xPtr = & x; // xPtr now points to address of x
yPtr = xPtr; // now yPtr and xPtr point to x
Computer Skills2 for Scientific
Colleges
6
Pointer Arithmetic
• Increment / decrement pointers ( ++ or -- )
• Add / subtract an integer to/from a pointer
( + or += , - or -= )
• Pointers may be subtracted from each other
• Pointer arithmetic is meaningless unless
performed on an array
Computer Skills2 for Scientific
Colleges
7
Pointer Arithmetic (Cont.)
• Example
Consider an integer array of 5 elements on a machine using 4
bytes for integers.
1000 1004 1008 1012 1016
Pointer variable vPtr
- vPtr pointes to first element V[0] (location 1000)
i.e. vPtr = 1000
- vPtr +=2; sets vPtr to 1008
i.e. vPtr points to V[2]
V[0] V[1] V[2] V[3] V[4]
Computer Skills2 for Scientific
Colleges
8
Pointer Arithmetic (Cont.)
• Subtracting pointers
- Returns the number of elements between two
addresses
e.g. if v is an array and
vPtr1 = v[0];
vPtr2 = v[2];
then vPtr2 – vPtr1 = 2 (i.e. 2 addresses)
Computer Skills2 for Scientific
Colleges
9
Relations Between Pointers and Arrays
• Arrays and pointers are closely related.
- Array name is like constant pointer
- Pointers can do array subscribing operations
- If we declare an array A[4] and a pointer aPtr
 aPtr is equal to A
aPtr == A
 aPtr is equal to the address of the first
element of A
aPtr == & A[0]
Computer Skills2 for Scientific
Colleges
10
Relations Between Pointers and Arrays (Cont.)
• Accessing array elements with pointers:
- Element A[i] can be accessed by *(aPtr+i)
 This is called pointer/offset notation
- Array itself can use pointer arithmetic
 A[3] is same as *(A+3)
- Pointers can be subscripted
(i.e. pointer/subscript notation)
 aPtr [3] is same as A[3]
Computer Skills2 for Scientific
Colleges
11
Examples on Pointers
//File: swap.cpp
//A program to call a function to swap two numbers using reference parameters
#include <iostream.h>
void swap(int *, int *); // This is swap's prototype
void main()
{ int x = 5, y = 7;
swap(&x , &y); // calling swap with reference parameters
cout << "n x is now "<< x << " and y is now " << y << 'n';
}
// swap function is defined here using dereferencing operator ‘*’
void swap(int *a, int *b)
{ int temp;
temp = *a;
*a = *b;
*b = temp;
}
Computer Skills2 for Scientific
Colleges
12
Examples on Pointers (Cont.)
//File: pointers.cpp
//A program to test pointers and references
#include <iostream.h>
void main ( )
{ int intVar = 10;
int *intPtr; // intPtr is a pointer
intPtr = & intVar;
cout << "nLocation of intVar: " << & intVar;
cout << "nContents of intVar: " << intVar;
cout << "nLocation of intPtr: " << & intPtr;
cout << "nContents of intPtr: " << intPtr;
cout << "nThe value that intPtr points to: " << * intPtr;
}
Computer Skills2 for Scientific
Colleges
13
Pointers and Strings
• Pointers can be used to declare strings and with string
functions (see next lecture slides)
When calling, the pointer formal parameter will points to the
actual parameter.
#include <iostream.h>
void Increment(int*);
void main() {
int A = 10;
Increment(&A);
cout<<A<<endl;
}
void Increment(int *X) { ++*X; }
Computer Skills2 for Scientific
Colleges
14
Ad

More Related Content

Similar to Programming fundamentals 2:pointers in c++ clearly explained (20)

divergence in intelligent ppis in gastro patients.ppt
divergence in intelligent ppis in gastro patients.pptdivergence in intelligent ppis in gastro patients.ppt
divergence in intelligent ppis in gastro patients.ppt
DjangoVijay
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
Sabaunnisa3
 
Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .
karimibaryal1996
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
ssusere19c741
 
See through C
See through CSee through C
See through C
Tushar B Kute
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
ShivamChaturvedi67
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
sangeeta borde
 
Pointers are one of the core components of the C programming language.
Pointers are one of the core components of the C programming language.Pointers are one of the core components of the C programming language.
Pointers are one of the core components of the C programming language.
bhargavi804095
 
08-Pointers.docx An array is a linear data structure
08-Pointers.docx An array is a linear data structure08-Pointers.docx An array is a linear data structure
08-Pointers.docx An array is a linear data structure
bhargavi804095
 
Pointers
PointersPointers
Pointers
NabishaAK
 
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptxComputer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
ab11167
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
SwapnaliPawar27
 
Pointers
PointersPointers
Pointers
Frijo Francis
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
Tushar B Kute
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptx
happycocoman
 
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dnU3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
mit23cs
 
divergence in intelligent ppis in gastro patients.ppt
divergence in intelligent ppis in gastro patients.pptdivergence in intelligent ppis in gastro patients.ppt
divergence in intelligent ppis in gastro patients.ppt
DjangoVijay
 
Pointers in C++ object oriented programming
Pointers in C++ object oriented programmingPointers in C++ object oriented programming
Pointers in C++ object oriented programming
Ahmad177077
 
Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .Introduction to pointers in c plus plus .
Introduction to pointers in c plus plus .
karimibaryal1996
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
ssusere19c741
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
sangeeta borde
 
Pointers are one of the core components of the C programming language.
Pointers are one of the core components of the C programming language.Pointers are one of the core components of the C programming language.
Pointers are one of the core components of the C programming language.
bhargavi804095
 
08-Pointers.docx An array is a linear data structure
08-Pointers.docx An array is a linear data structure08-Pointers.docx An array is a linear data structure
08-Pointers.docx An array is a linear data structure
bhargavi804095
 
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptxComputer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
ab11167
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
Tushar B Kute
 
Engineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptxEngineering Computers L32-L33-Pointers.pptx
Engineering Computers L32-L33-Pointers.pptx
happycocoman
 
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dnU3_4_PointerArithmetic.pdf people will use the above preaentationa dn
U3_4_PointerArithmetic.pdf people will use the above preaentationa dn
mit23cs
 

Recently uploaded (20)

APM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdfAPM Midlands Region April 2025 Sacha Hind Circulated.pdf
APM Midlands Region April 2025 Sacha Hind Circulated.pdf
Association for Project Management
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptxLecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Arshad Shaikh
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
Debunking the Myths behind AI - v1, Carl Dalby
Debunking the Myths behind AI -  v1, Carl DalbyDebunking the Myths behind AI -  v1, Carl Dalby
Debunking the Myths behind AI - v1, Carl Dalby
Association for Project Management
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx   quiz by Ridip HazarikaTHE STG QUIZ GROUP D.pptx   quiz by Ridip Hazarika
THE STG QUIZ GROUP D.pptx quiz by Ridip Hazarika
Ridip Hazarika
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptxLecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Arshad Shaikh
 
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
BỘ ĐỀ TUYỂN SINH VÀO LỚP 10 TIẾNG ANH - 25 ĐỀ THI BÁM SÁT CẤU TRÚC MỚI NHẤT, ...
Nguyen Thanh Tu Collection
 
Sugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptxSugar-Sensing Mechanism in plants....pptx
Sugar-Sensing Mechanism in plants....pptx
Dr. Renu Jangid
 
Lecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptxLecture 1 Introduction history and institutes of entomology_1.pptx
Lecture 1 Introduction history and institutes of entomology_1.pptx
Arshad Shaikh
 
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdfRanking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Ranking_Felicidade_2024_com_Educacao_Marketing Educacional_V2.pdf
Rafael Villas B
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
Herbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptxHerbs Used in Cosmetic Formulations .pptx
Herbs Used in Cosmetic Formulations .pptx
RAJU THENGE
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Ad

Programming fundamentals 2:pointers in c++ clearly explained

  • 1. Programming fundamentals 2 Chapter 3:Pointer Miss:Hanan Hardam 1
  • 2. Computer Skills2 for Scientific Colleges 2 Pointers in C++ Topics to cover: • Overview of Pointers • Pointer Declaration • Pointer Assignment • Pointer Arithmetic • Relations Between Pointers and Arrays • Pointers and Strings
  • 3. Computer Skills2 for Scientific Colleges 3 Overview of Pointers • A Pointer in C++ is variable whose value is a memory address. • With pointers many memory locations can be referenced. • Some data structures use pointers (e.g. linked list, tree). • The * and & operators - & operator is the address operator - * operator is the dereferencing operator. It is used in pointers declaration
  • 4. Computer Skills2 for Scientific Colleges 4 Pointer Declaration • Pointers are declared as follows: <type> * variable_name ; e.g. int * xPtr; // xPtr is a pointer to data of type integer char * cPtr; //cPtr is a pointer to data of type character void * yPtr; // yPtr is a generic pointer, // represents any type
  • 5. Computer Skills2 for Scientific Colleges 5 Pointer Assignment • Assignment can be applied on pointers of the same type • If not the same type, a cast operator must be used • Exception: pointer to void does not need casting to convert a pointer to void type • void pointers cannot be dereferenced • Example int *xPtr, *yPtr; int x = 5; … xPtr = & x; // xPtr now points to address of x yPtr = xPtr; // now yPtr and xPtr point to x
  • 6. Computer Skills2 for Scientific Colleges 6 Pointer Arithmetic • Increment / decrement pointers ( ++ or -- ) • Add / subtract an integer to/from a pointer ( + or += , - or -= ) • Pointers may be subtracted from each other • Pointer arithmetic is meaningless unless performed on an array
  • 7. Computer Skills2 for Scientific Colleges 7 Pointer Arithmetic (Cont.) • Example Consider an integer array of 5 elements on a machine using 4 bytes for integers. 1000 1004 1008 1012 1016 Pointer variable vPtr - vPtr pointes to first element V[0] (location 1000) i.e. vPtr = 1000 - vPtr +=2; sets vPtr to 1008 i.e. vPtr points to V[2] V[0] V[1] V[2] V[3] V[4]
  • 8. Computer Skills2 for Scientific Colleges 8 Pointer Arithmetic (Cont.) • Subtracting pointers - Returns the number of elements between two addresses e.g. if v is an array and vPtr1 = v[0]; vPtr2 = v[2]; then vPtr2 – vPtr1 = 2 (i.e. 2 addresses)
  • 9. Computer Skills2 for Scientific Colleges 9 Relations Between Pointers and Arrays • Arrays and pointers are closely related. - Array name is like constant pointer - Pointers can do array subscribing operations - If we declare an array A[4] and a pointer aPtr  aPtr is equal to A aPtr == A  aPtr is equal to the address of the first element of A aPtr == & A[0]
  • 10. Computer Skills2 for Scientific Colleges 10 Relations Between Pointers and Arrays (Cont.) • Accessing array elements with pointers: - Element A[i] can be accessed by *(aPtr+i)  This is called pointer/offset notation - Array itself can use pointer arithmetic  A[3] is same as *(A+3) - Pointers can be subscripted (i.e. pointer/subscript notation)  aPtr [3] is same as A[3]
  • 11. Computer Skills2 for Scientific Colleges 11 Examples on Pointers //File: swap.cpp //A program to call a function to swap two numbers using reference parameters #include <iostream.h> void swap(int *, int *); // This is swap's prototype void main() { int x = 5, y = 7; swap(&x , &y); // calling swap with reference parameters cout << "n x is now "<< x << " and y is now " << y << 'n'; } // swap function is defined here using dereferencing operator ‘*’ void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; }
  • 12. Computer Skills2 for Scientific Colleges 12 Examples on Pointers (Cont.) //File: pointers.cpp //A program to test pointers and references #include <iostream.h> void main ( ) { int intVar = 10; int *intPtr; // intPtr is a pointer intPtr = & intVar; cout << "nLocation of intVar: " << & intVar; cout << "nContents of intVar: " << intVar; cout << "nLocation of intPtr: " << & intPtr; cout << "nContents of intPtr: " << intPtr; cout << "nThe value that intPtr points to: " << * intPtr; }
  • 13. Computer Skills2 for Scientific Colleges 13 Pointers and Strings • Pointers can be used to declare strings and with string functions (see next lecture slides)
  • 14. When calling, the pointer formal parameter will points to the actual parameter. #include <iostream.h> void Increment(int*); void main() { int A = 10; Increment(&A); cout<<A<<endl; } void Increment(int *X) { ++*X; } Computer Skills2 for Scientific Colleges 14