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?

More Related Content

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

PPTX
C++ FUNCTIONS-1.pptx
ShashiShash2
 
PPTX
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
PPT
Advanced pointers
Koganti Ravikumar
 
PDF
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
drsomeshdewangan
 
PPT
Unit 6 pointers
George Erfesoglou
 
PPTX
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
PPT
Pointer
Fahuda E
 
PPTX
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
PPTX
Pointer in C++
Mauryasuraj98
 
PDF
C++_notes.pdf
HimanshuSharma997566
 
PPTX
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
PPT
Programming in Computer Science- Pointers in C++.ppt
richardbaahnkansah
 
PPT
Lecture2.ppt
Sabaunnisa3
 
PPSX
Pointers
Frijo Francis
 
DOCX
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
PPTX
pointer.pptx module of information technology
jolynetomas
 
DOCX
Arrry structure Stacks in data structure
lodhran-hayat
 
PDF
Pointers
Hitesh Wagle
 
C++ FUNCTIONS-1.pptx
ShashiShash2
 
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
Advanced pointers
Koganti Ravikumar
 
Pointer in C++_Somesh_Kumar_Dewangan_SSTC
drsomeshdewangan
 
Unit 6 pointers
George Erfesoglou
 
Pf cs102 programming-9 [pointers]
Abdullah khawar
 
Pointer
Fahuda E
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
Pointer in C++
Mauryasuraj98
 
C++_notes.pdf
HimanshuSharma997566
 
arraytypes of array and pointer string in c++.pptx
harinipradeep15
 
Programming in Computer Science- Pointers in C++.ppt
richardbaahnkansah
 
Lecture2.ppt
Sabaunnisa3
 
Pointers
Frijo Francis
 
C++ Pointers with Examples.docx
JoeyDelaCruz22
 
pointer.pptx module of information technology
jolynetomas
 
Arrry structure Stacks in data structure
lodhran-hayat
 
Pointers
Hitesh Wagle
 

More from Ahmad177077 (12)

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

Recently uploaded (20)

PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
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