SlideShare a Scribd company logo
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 1
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Pointer :
Definition
In C++, a pointer is a variable that stores the memory address of another variable. Pointers
are a powerful feature that allow you to work with memory directly and are useful in
situations where you need dynamic memory allocation, to pass data by reference, or to
interact with hardware or low-level system components.
Basic Syntax and Example
Here's the basic syntax to declare a pointer:
type* pointer_name;
• type is the data type of the variable that the pointer will point to.
• * indicates that pointer_name is a pointer.
For example:
int* ptr; // declares a pointer to an int
Key Concepts
1. Pointer Declaration: Declares a pointer of a specific type, like int* or double*.
int* ptr; // ptr is a pointer to an integer
2. Address-of Operator (&): Used to get the memory address of a variable.
int num = 10;
ptr = # // ptr now holds the address of num
3. Dereference Operator (*): Used to access or modify the value at the memory
address a pointer is pointing to.
cout << *ptr; // outputs the value of num (10) by dereferencing ptr
4. Null Pointers: A pointer that is not assigned any address is called a null pointer,
usually initialized as nullptr in modern C++.
int* ptr = nullptr; // ptr is now a null pointer
demonstrating pointers:
#include <iostream>
using namespace std;
int main() {
int num = 10; // An integer variable
int* ptr = &num; // Pointer to an integer, initialized to the address of num
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 2
SHRI SHANKARACHARYA TECHNICAL CAMPUS
cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num << endl;
cout << "Pointer value (address of num): " << ptr << endl;
cout << "Dereferenced pointer value (*ptr): " << *ptr << endl;
*ptr = 20; // Changing the value of num using the pointer
cout << "Updated value of num: " << num << endl;
return 0;
}
Output
yaml
Value of num: 10
Address of num: 0x7ffeeb2d4c28 (example address)
Pointer value (address of num): 0x7ffeeb2d4c28
Dereferenced pointer value (*ptr): 10
Updated value of num: 20
Pointers allow manipulation of data directly in memory.
They enable dynamic memory allocation, which is essential for certain programming tasks.
C++ provides advanced pointer types, like smart pointers (std::unique_ptr, std::shared_ptr),
which help with memory management and avoid common errors.
• Dereferencing (*ptr): Allows access to the value at the address stored in the pointer.
• Address-of Operator (&var): Gives the address of the variable var.
• Type Safety: The data type of a pointer must match the data type of the variable it
points to (e.g., int * for integers, char * for characters).
• Null Pointer: A pointer can be initialized to nullptr to indicate that it doesn’t point to
any valid memory address.
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 3
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Declaring and Initializing a Pointer
1. Declaration: A pointer variable is declared with an asterisk * before its name.
2. Initialization: A pointer can be assigned the address of another variable using the
address-of operator &.
Pointer to an Integer
#include <iostream>
using namespace std;
int main() {
int num = 10; // Regular integer variable
int *ptr = &num; // Pointer to an integer, initialized with the address of 'num'
cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num << endl;
cout << "Value stored in pointer ptr: " << ptr << endl;
cout << "Value pointed to by ptr: " << *ptr << endl;
return 0;
}
Pointer to a Character
#include <iostream>
using namespace std;
int main() {
char ch = 'A'; // Regular character variable
char *charPtr = &ch; // Pointer to a character, initialized with the address of 'ch'
cout << "Value of ch: " << ch << endl;
cout << "Address of ch: " << static_cast<void*>(&ch) << endl;
cout << "Value stored in pointer charPtr: " << static_cast<void*>(charPtr) << endl;
cout << "Value pointed to by charPtr: " << *charPtr << endl;
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 4
SHRI SHANKARACHARYA TECHNICAL CAMPUS
return 0;
}
Explanation
• In Program 1 demonstrates a pointer to an integer, showing how to access the
address and value of num through the pointer.
• In Program 2 demonstrates a pointer to a character, which can be useful for handling
strings or single characters in memory.
In C++, We have derived pointers are variables that store the address of another variable
rather than a direct value. Pointers are powerful tools in C++ that allow you to manage
memory directly and efficiently, perform dynamic memory allocation, manipulate arrays, and
enable efficient function parameter passing.
Declaring and Initializing a Pointer
1. Declaration: To declare a pointer, use the syntax:
<data_type> *pointer_name;
o data_type is the type of the variable the pointer will point to.
o The * symbol indicates that pointer_name is a pointer to a variable of type
data_type.
2. Initialization: After declaration, a pointer can be initialized by assigning it the
address of a variable using the & (address-of) operator. The address-of operator gets
the memory address of a variable.
int var = 5;
int *ptr = &var; // ptr is now holding the address of var
Here, ptr is a pointer to an integer, and it holds the address of var.
Pointer to an Integer
We have declared an integer variable and a pointer to that integer. The pointer is initialized
with the address of the integer variable. This example also demonstrates accessing the
integer’s value through the pointer.
#include <iostream>
using namespace std;
int main() {
int number = 20; // Declare and initialize an integer
int *ptr = &number; // Declare a pointer to int, initialize it with the address of 'number'
// Display the value and address of the variable
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 5
SHRI SHANKARACHARYA TECHNICAL CAMPUS
cout << "Value of number: " << number << endl;
cout << "Address of number: " << &number << endl;
// Display the value stored in the pointer and the value pointed to by the pointer
cout << "Value stored in pointer ptr: " << ptr << endl;
cout << "Value pointed to by ptr (dereferencing): " << *ptr << endl;
return 0;
}
Explanation
• number is an integer variable with the value 20.
• ptr is an integer pointer that holds the address of number.
• *ptr (dereferencing ptr) gives the value of the variable that ptr points to, which is 20.
Pointer to a Character
A pointer to a character variable. The pointer is initialized with the address of the character
variable, and we access both the address and the character’s value using the pointer.
#include <iostream>
using namespace std;
int main() {
char letter = 'A'; // Declare and initialize a character
char *charPtr = &letter; // Declare a pointer to char, initialize it with the address of
'letter'
// Display the value and address of the character variable
cout << "Value of letter: " << letter << endl;
cout << "Address of letter: " << static_cast<void*>(&letter) << endl;
// Display the value stored in the pointer and the value pointed to by the pointer
cout << "Value stored in pointer charPtr: " << static_cast<void*>(charPtr) << endl;
cout << "Value pointed to by charPtr (dereferencing): " << *charPtr << endl;
return 0;
}
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 6
SHRI SHANKARACHARYA TECHNICAL CAMPUS
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 7
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Explanation
• letter is a character variable initialized with 'A'.
• charPtr is a character pointer that stores the address of letter.
• *charPtr (dereferencing charPtr) provides the value stored at the memory location it
points to, which is 'A'.
Accessing Data Through Pointers
In C++, a pointer stores the memory address of another variable. Accessing data through
pointers involves using the address-of operator (&) to store an address in a pointer and the
dereference operator (*) to retrieve or modify the data stored at that address.
Example
#include <iostream>
using namespace std;
int main() {
int num = 42; // Declare an integer variable
int* ptr = &num; // Pointer to int, storing address of num
// Accessing value through the pointer
cout << "Value of num using pointer: " << *ptr << endl; // Outputs 42
// Modifying value through the pointer
*ptr = 50;
cout << "Updated value of num: " << num << endl; // Outputs 50
return 0;
}
Here, ptr holds the address of num. By dereferencing *ptr, we can access and modify num.
2. Pointer Arithmetic
Pointer arithmetic is a way to move through memory using pointers. When performing
arithmetic on pointers, the compiler moves the pointer by a number of bytes corresponding to
the type it points to (e.g., +1 moves by sizeof(type) bytes).
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40}; // An integer array
int* ptr = arr; // Pointer to the first element of the array
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 8
SHRI SHANKARACHARYA TECHNICAL CAMPUS
cout << "First element: " << *ptr << endl; // Outputs 10
cout << "Second element: " << *(ptr + 1) << endl; // Outputs 20
cout << "Third element: " << *(ptr + 2) << endl; // Outputs 30
// Increment the pointer to point to the next element
ptr++;
cout << "After increment, pointer points to: " << *ptr << endl; // Outputs 20
return 0;
}
3. Pointer to an Object
In C++, pointers can also point to objects, allowing direct access to members of an object. We
use the -> operator (arrow operator) with pointers to access an object's members.
#include <iostream>
using namespace std;
class MyClass {
public:
int data;
void showData() {
cout << "Data: " << data << endl;
}
};
int main() {
MyClass obj; // Create an object
MyClass* ptr = &obj; // Pointer to the object
ptr->data = 100; // Using arrow operator to access data member
ptr->showData(); // Using arrow operator to call a member function
return 0;
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 9
SHRI SHANKARACHARYA TECHNICAL CAMPUS
}
Here, ptr points to obj, and we use ptr->data and ptr->showData() to access and modify its
members.
4. this Pointer
this pointer is an implicit pointer available inside non-static member functions of a class. It
points to the object that invokes the member function. It’s useful when you want to refer to
the current object's members explicitly.
Example
#include <iostream>
using namespace std;
class MyClass {
private:
int data;
public:
MyClass(int data) {
this->data = data; // `this->data` refers to the object's member variable
}
void showData() {
cout << "Data: " << this->data << endl;
}
};
int main() {
MyClass obj(42); // Create an object with data=42
obj.showData(); // Outputs "Data: 42"
return 0;
}
Here, this->data refers to the data member of the object, helping distinguish it from the
constructor parameter data.
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 10
SHRI SHANKARACHARYA TECHNICAL CAMPUS
5. Pointer-Related Problems
While pointers are powerful, they can lead to certain issues if not handled carefully:
Dangling Pointers
A dangling pointer arises when a pointer points to a memory location that has been
deallocated or is out of scope. Accessing a dangling pointer can lead to undefined behavior,
crashes, or data corruption.
int* ptr;
{
int temp = 10;
ptr = &temp; // ptr points to temp's memory location
} // temp goes out of scope here
// ptr is now a dangling pointer, pointing to invalid memory
cout << *ptr; // Undefined behavior!
Solutions:
• Set pointers to nullptr after deleting or nullify them when they go out of scope.
• Use smart pointers, which automatically deallocate memory when no longer needed.
Wild Pointers
A wild pointer is an uninitialized pointer that does not point to any valid memory address.
Using a wild pointer can lead to crashes or unpredictable behavior.
int* ptr; // ptr is a wild pointer, not initialized to any valid address
*ptr = 10; // Undefined behavior!
Solutions:
• Always initialize pointers to nullptr or a valid memory address.
Memory Leaks
Memory leaks occur when dynamically allocated memory is not deallocated properly, leading
to memory wastage.
int* ptr = new int(42); // Dynamically allocate memory
// ... forgot to delete ptr
// Memory leak: allocated memory is not released
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 11
SHRI SHANKARACHARYA TECHNICAL CAMPUS
Solutions:
• Always delete dynamically allocated memory with delete (for single variables) or
delete[] (for arrays).
• Use smart pointers like std::unique_ptr and std::shared_ptr from C++11, which handle
memory management automatically.
Null Pointer Assignment
A null pointer in programming is a pointer that doesn’t point to any valid memory address.
In C++, assigning a pointer to nullptr or NULL means the pointer is intentionally pointing to
"nothing." However, using or dereferencing a null pointer causes errors, as it doesn’t hold a
valid memory address.
Dereferencing a Null Pointer
a pointer is initialized to nullptr and then mistakenly dereferenced.
#include <iostream>
int main() {
int *ptr = nullptr; // Assigning null to the pointer
*ptr = 5; // Attempting to dereference a null pointer (undefined behavior)
std::cout << *ptr << std::endl;
return 0;
}
Explanation: Here, ptr is set to nullptr, which means it doesn’t point to any actual data.
When we try to dereference *ptr, the program attempts to access an invalid memory location,
leading to undefined behavior or a runtime error.
Dangling Pointer after delete
A dangling pointer occurs when a pointer still holds the address of memory that’s been
deallocated. Here, it’s crucial to set the pointer to nullptr after deleting it.
#include <iostream>
int main() {
int *ptr = new int(10); // Allocate memory
delete ptr; // Free memory
*ptr = 20; // Attempt to use a deleted pointer (undefined behavior)
std::cout << *ptr << std::endl;
return 0;
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 12
SHRI SHANKARACHARYA TECHNICAL CAMPUS
}
Explanation: After deleting ptr, it no longer points to a valid memory location, but it still
holds an address. Using or dereferencing *ptr after deletion leads to undefined behaviour. To
prevent this, set ptr to nullptr after delete:
delete ptr;
ptr = nullptr; // Now `ptr` is a null pointer, safer if used by mistake
Dynamic Memory Management Using new and delete
Dynamic memory management in C++ is achieved using the new and delete operators, which
allocate and deallocate memory at runtime, rather than compile-time. This approach is useful
for creating data structures like arrays or objects whose size or lifetime may not be known
until runtime.
1. new Operator: Allocates memory on the heap and returns a pointer to that memory.
2. delete Operator: Deallocates memory allocated with new.
Allocating and Deleting a Single Integer
Using new and delete to dynamically manage a single integer.
#include <iostream>
int main() {
int *ptr = new int(25); // Allocate memory for an integer and initialize it to 25
std::cout << "Value: " << *ptr << std::endl;
delete ptr; // Deallocate the memory
ptr = nullptr; // Set pointer to null to avoid dangling pointer
return 0;
}
Explanation:
• new int(25) allocates memory for an integer and initializes it to 25.
• delete ptr deallocates the memory.
• Setting ptr to nullptr after deletion prevents accidental use of a dangling pointer.
Example 2: Dynamic Array Allocation and Deallocation
Using new and delete[] to allocate and delete an array dynamically.
cpp
Copy code
#include <iostream>
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 13
SHRI SHANKARACHARYA TECHNICAL CAMPUS
int main() {
int *arr = new int[5]; // Dynamically allocate an array of 5 integers
// Initialize array elements
for (int i = 0; i < 5; ++i) {
arr[i] = i * 2; // Set each element to twice its index
}
// Output array elements
for (int i = 0; i < 5; ++i) {
std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
}
delete[] arr; // Deallocate the array
arr = nullptr; // Set pointer to null to avoid dangling pointer
return 0;
}
Explanation:
• new int[5] allocates an array of 5 integers.
• delete[] arr frees the memory allocated for the array.
• Setting arr to nullptr helps prevent accidental access to the deallocated memory.
• Null Pointer Assignment: Dereferencing or using a null pointer or a pointer that
points to deleted memory can cause runtime errors. Always initialize pointers and set
them to nullptr after delete.
• Dynamic Memory Management: Use new and delete to manage memory
dynamically, but match every new with a delete (and new[] with delete[]) to avoid
SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 14
SHRI SHANKARACHARYA TECHNICAL CAMPUS
memory leaks. Smart pointers (e.g., std::unique_ptr or std::shared_ptr) can be
preferable for automatic memory management.

More Related Content

PPTX
Object Oriented Programming using C++: Ch10 Pointers.pptx
PPTX
Introduction to pointers in c plus plus .
PPTX
Pointers in C++ object oriented programming
PPTX
Computer Programming Lecture numer 05 -- pointers,variablesb
PPT
Unit 6 pointers
PPTX
Pointer in C
PDF
PSPC--UNIT-5.pdf
PPTX
Pointer Basics,Constant Pointers & Pointer to Constant.
Object Oriented Programming using C++: Ch10 Pointers.pptx
Introduction to pointers in c plus plus .
Pointers in C++ object oriented programming
Computer Programming Lecture numer 05 -- pointers,variablesb
Unit 6 pointers
Pointer in C
PSPC--UNIT-5.pdf
Pointer Basics,Constant Pointers & Pointer to Constant.

Similar to Pointer in C++_Somesh_Kumar_Dewangan_SSTC (20)

ODP
Pointers in c++ by minal
PPTX
pointers.pptx
PPTX
C++ Pointer | Introduction to programming
PPTX
Unit-I Pointer Data structure.pptx
PPT
Lecture2.ppt
PPTX
COM1407: Working with Pointers
PPTX
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
PPTX
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
PPTX
C++ FUNCTIONS-1.pptx
PPTX
L4_Pointer Arithmetic in C++.pptxhwhwjwjw
PPT
Pointers
PPT
Pointer
PPTX
Pf cs102 programming-9 [pointers]
PDF
Chapter 5 (Part I) - Pointers.pdf
PPTX
Pointers and single &multi dimentionalarrays.pptx
PPTX
Pointers in c++ programming presentation
PPTX
Array in C newrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
PDF
Chapter16 pointer
PPT
Pointers (Pp Tminimizer)
PPTX
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
Pointers in c++ by minal
pointers.pptx
C++ Pointer | Introduction to programming
Unit-I Pointer Data structure.pptx
Lecture2.ppt
COM1407: Working with Pointers
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
C++ FUNCTIONS-1.pptx
L4_Pointer Arithmetic in C++.pptxhwhwjwjw
Pointers
Pointer
Pf cs102 programming-9 [pointers]
Chapter 5 (Part I) - Pointers.pdf
Pointers and single &multi dimentionalarrays.pptx
Pointers in c++ programming presentation
Array in C newrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Chapter16 pointer
Pointers (Pp Tminimizer)
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
Ad

Recently uploaded (20)

DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPT
Project quality management in manufacturing
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
web development for engineering and engineering
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
DOCX
573137875-Attendance-Management-System-original
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Geodesy 1.pptx...............................................
PDF
PPT on Performance Review to get promotions
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
composite construction of structures.pdf
PDF
Well-logging-methods_new................
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Welding lecture in detail for understanding
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Project quality management in manufacturing
Foundation to blockchain - A guide to Blockchain Tech
web development for engineering and engineering
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
573137875-Attendance-Management-System-original
bas. eng. economics group 4 presentation 1.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Geodesy 1.pptx...............................................
PPT on Performance Review to get promotions
CYBER-CRIMES AND SECURITY A guide to understanding
composite construction of structures.pdf
Well-logging-methods_new................
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Welding lecture in detail for understanding
Ad

Pointer in C++_Somesh_Kumar_Dewangan_SSTC

  • 1. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 1 SHRI SHANKARACHARYA TECHNICAL CAMPUS Pointer : Definition In C++, a pointer is a variable that stores the memory address of another variable. Pointers are a powerful feature that allow you to work with memory directly and are useful in situations where you need dynamic memory allocation, to pass data by reference, or to interact with hardware or low-level system components. Basic Syntax and Example Here's the basic syntax to declare a pointer: type* pointer_name; • type is the data type of the variable that the pointer will point to. • * indicates that pointer_name is a pointer. For example: int* ptr; // declares a pointer to an int Key Concepts 1. Pointer Declaration: Declares a pointer of a specific type, like int* or double*. int* ptr; // ptr is a pointer to an integer 2. Address-of Operator (&): Used to get the memory address of a variable. int num = 10; ptr = &num; // ptr now holds the address of num 3. Dereference Operator (*): Used to access or modify the value at the memory address a pointer is pointing to. cout << *ptr; // outputs the value of num (10) by dereferencing ptr 4. Null Pointers: A pointer that is not assigned any address is called a null pointer, usually initialized as nullptr in modern C++. int* ptr = nullptr; // ptr is now a null pointer demonstrating pointers: #include <iostream> using namespace std; int main() { int num = 10; // An integer variable int* ptr = &num; // Pointer to an integer, initialized to the address of num
  • 2. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 2 SHRI SHANKARACHARYA TECHNICAL CAMPUS cout << "Value of num: " << num << endl; cout << "Address of num: " << &num << endl; cout << "Pointer value (address of num): " << ptr << endl; cout << "Dereferenced pointer value (*ptr): " << *ptr << endl; *ptr = 20; // Changing the value of num using the pointer cout << "Updated value of num: " << num << endl; return 0; } Output yaml Value of num: 10 Address of num: 0x7ffeeb2d4c28 (example address) Pointer value (address of num): 0x7ffeeb2d4c28 Dereferenced pointer value (*ptr): 10 Updated value of num: 20 Pointers allow manipulation of data directly in memory. They enable dynamic memory allocation, which is essential for certain programming tasks. C++ provides advanced pointer types, like smart pointers (std::unique_ptr, std::shared_ptr), which help with memory management and avoid common errors. • Dereferencing (*ptr): Allows access to the value at the address stored in the pointer. • Address-of Operator (&var): Gives the address of the variable var. • Type Safety: The data type of a pointer must match the data type of the variable it points to (e.g., int * for integers, char * for characters). • Null Pointer: A pointer can be initialized to nullptr to indicate that it doesn’t point to any valid memory address.
  • 3. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 3 SHRI SHANKARACHARYA TECHNICAL CAMPUS Declaring and Initializing a Pointer 1. Declaration: A pointer variable is declared with an asterisk * before its name. 2. Initialization: A pointer can be assigned the address of another variable using the address-of operator &. Pointer to an Integer #include <iostream> using namespace std; int main() { int num = 10; // Regular integer variable int *ptr = &num; // Pointer to an integer, initialized with the address of 'num' cout << "Value of num: " << num << endl; cout << "Address of num: " << &num << endl; cout << "Value stored in pointer ptr: " << ptr << endl; cout << "Value pointed to by ptr: " << *ptr << endl; return 0; } Pointer to a Character #include <iostream> using namespace std; int main() { char ch = 'A'; // Regular character variable char *charPtr = &ch; // Pointer to a character, initialized with the address of 'ch' cout << "Value of ch: " << ch << endl; cout << "Address of ch: " << static_cast<void*>(&ch) << endl; cout << "Value stored in pointer charPtr: " << static_cast<void*>(charPtr) << endl; cout << "Value pointed to by charPtr: " << *charPtr << endl;
  • 4. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 4 SHRI SHANKARACHARYA TECHNICAL CAMPUS return 0; } Explanation • In Program 1 demonstrates a pointer to an integer, showing how to access the address and value of num through the pointer. • In Program 2 demonstrates a pointer to a character, which can be useful for handling strings or single characters in memory. In C++, We have derived pointers are variables that store the address of another variable rather than a direct value. Pointers are powerful tools in C++ that allow you to manage memory directly and efficiently, perform dynamic memory allocation, manipulate arrays, and enable efficient function parameter passing. Declaring and Initializing a Pointer 1. Declaration: To declare a pointer, use the syntax: <data_type> *pointer_name; o data_type is the type of the variable the pointer will point to. o The * symbol indicates that pointer_name is a pointer to a variable of type data_type. 2. Initialization: After declaration, a pointer can be initialized by assigning it the address of a variable using the & (address-of) operator. The address-of operator gets the memory address of a variable. int var = 5; int *ptr = &var; // ptr is now holding the address of var Here, ptr is a pointer to an integer, and it holds the address of var. Pointer to an Integer We have declared an integer variable and a pointer to that integer. The pointer is initialized with the address of the integer variable. This example also demonstrates accessing the integer’s value through the pointer. #include <iostream> using namespace std; int main() { int number = 20; // Declare and initialize an integer int *ptr = &number; // Declare a pointer to int, initialize it with the address of 'number' // Display the value and address of the variable
  • 5. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 5 SHRI SHANKARACHARYA TECHNICAL CAMPUS cout << "Value of number: " << number << endl; cout << "Address of number: " << &number << endl; // Display the value stored in the pointer and the value pointed to by the pointer cout << "Value stored in pointer ptr: " << ptr << endl; cout << "Value pointed to by ptr (dereferencing): " << *ptr << endl; return 0; } Explanation • number is an integer variable with the value 20. • ptr is an integer pointer that holds the address of number. • *ptr (dereferencing ptr) gives the value of the variable that ptr points to, which is 20. Pointer to a Character A pointer to a character variable. The pointer is initialized with the address of the character variable, and we access both the address and the character’s value using the pointer. #include <iostream> using namespace std; int main() { char letter = 'A'; // Declare and initialize a character char *charPtr = &letter; // Declare a pointer to char, initialize it with the address of 'letter' // Display the value and address of the character variable cout << "Value of letter: " << letter << endl; cout << "Address of letter: " << static_cast<void*>(&letter) << endl; // Display the value stored in the pointer and the value pointed to by the pointer cout << "Value stored in pointer charPtr: " << static_cast<void*>(charPtr) << endl; cout << "Value pointed to by charPtr (dereferencing): " << *charPtr << endl; return 0; }
  • 6. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 6 SHRI SHANKARACHARYA TECHNICAL CAMPUS
  • 7. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 7 SHRI SHANKARACHARYA TECHNICAL CAMPUS Explanation • letter is a character variable initialized with 'A'. • charPtr is a character pointer that stores the address of letter. • *charPtr (dereferencing charPtr) provides the value stored at the memory location it points to, which is 'A'. Accessing Data Through Pointers In C++, a pointer stores the memory address of another variable. Accessing data through pointers involves using the address-of operator (&) to store an address in a pointer and the dereference operator (*) to retrieve or modify the data stored at that address. Example #include <iostream> using namespace std; int main() { int num = 42; // Declare an integer variable int* ptr = &num; // Pointer to int, storing address of num // Accessing value through the pointer cout << "Value of num using pointer: " << *ptr << endl; // Outputs 42 // Modifying value through the pointer *ptr = 50; cout << "Updated value of num: " << num << endl; // Outputs 50 return 0; } Here, ptr holds the address of num. By dereferencing *ptr, we can access and modify num. 2. Pointer Arithmetic Pointer arithmetic is a way to move through memory using pointers. When performing arithmetic on pointers, the compiler moves the pointer by a number of bytes corresponding to the type it points to (e.g., +1 moves by sizeof(type) bytes). #include <iostream> using namespace std; int main() { int arr[] = {10, 20, 30, 40}; // An integer array int* ptr = arr; // Pointer to the first element of the array
  • 8. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 8 SHRI SHANKARACHARYA TECHNICAL CAMPUS cout << "First element: " << *ptr << endl; // Outputs 10 cout << "Second element: " << *(ptr + 1) << endl; // Outputs 20 cout << "Third element: " << *(ptr + 2) << endl; // Outputs 30 // Increment the pointer to point to the next element ptr++; cout << "After increment, pointer points to: " << *ptr << endl; // Outputs 20 return 0; } 3. Pointer to an Object In C++, pointers can also point to objects, allowing direct access to members of an object. We use the -> operator (arrow operator) with pointers to access an object's members. #include <iostream> using namespace std; class MyClass { public: int data; void showData() { cout << "Data: " << data << endl; } }; int main() { MyClass obj; // Create an object MyClass* ptr = &obj; // Pointer to the object ptr->data = 100; // Using arrow operator to access data member ptr->showData(); // Using arrow operator to call a member function return 0;
  • 9. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 9 SHRI SHANKARACHARYA TECHNICAL CAMPUS } Here, ptr points to obj, and we use ptr->data and ptr->showData() to access and modify its members. 4. this Pointer this pointer is an implicit pointer available inside non-static member functions of a class. It points to the object that invokes the member function. It’s useful when you want to refer to the current object's members explicitly. Example #include <iostream> using namespace std; class MyClass { private: int data; public: MyClass(int data) { this->data = data; // `this->data` refers to the object's member variable } void showData() { cout << "Data: " << this->data << endl; } }; int main() { MyClass obj(42); // Create an object with data=42 obj.showData(); // Outputs "Data: 42" return 0; } Here, this->data refers to the data member of the object, helping distinguish it from the constructor parameter data.
  • 10. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 10 SHRI SHANKARACHARYA TECHNICAL CAMPUS 5. Pointer-Related Problems While pointers are powerful, they can lead to certain issues if not handled carefully: Dangling Pointers A dangling pointer arises when a pointer points to a memory location that has been deallocated or is out of scope. Accessing a dangling pointer can lead to undefined behavior, crashes, or data corruption. int* ptr; { int temp = 10; ptr = &temp; // ptr points to temp's memory location } // temp goes out of scope here // ptr is now a dangling pointer, pointing to invalid memory cout << *ptr; // Undefined behavior! Solutions: • Set pointers to nullptr after deleting or nullify them when they go out of scope. • Use smart pointers, which automatically deallocate memory when no longer needed. Wild Pointers A wild pointer is an uninitialized pointer that does not point to any valid memory address. Using a wild pointer can lead to crashes or unpredictable behavior. int* ptr; // ptr is a wild pointer, not initialized to any valid address *ptr = 10; // Undefined behavior! Solutions: • Always initialize pointers to nullptr or a valid memory address. Memory Leaks Memory leaks occur when dynamically allocated memory is not deallocated properly, leading to memory wastage. int* ptr = new int(42); // Dynamically allocate memory // ... forgot to delete ptr // Memory leak: allocated memory is not released
  • 11. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 11 SHRI SHANKARACHARYA TECHNICAL CAMPUS Solutions: • Always delete dynamically allocated memory with delete (for single variables) or delete[] (for arrays). • Use smart pointers like std::unique_ptr and std::shared_ptr from C++11, which handle memory management automatically. Null Pointer Assignment A null pointer in programming is a pointer that doesn’t point to any valid memory address. In C++, assigning a pointer to nullptr or NULL means the pointer is intentionally pointing to "nothing." However, using or dereferencing a null pointer causes errors, as it doesn’t hold a valid memory address. Dereferencing a Null Pointer a pointer is initialized to nullptr and then mistakenly dereferenced. #include <iostream> int main() { int *ptr = nullptr; // Assigning null to the pointer *ptr = 5; // Attempting to dereference a null pointer (undefined behavior) std::cout << *ptr << std::endl; return 0; } Explanation: Here, ptr is set to nullptr, which means it doesn’t point to any actual data. When we try to dereference *ptr, the program attempts to access an invalid memory location, leading to undefined behavior or a runtime error. Dangling Pointer after delete A dangling pointer occurs when a pointer still holds the address of memory that’s been deallocated. Here, it’s crucial to set the pointer to nullptr after deleting it. #include <iostream> int main() { int *ptr = new int(10); // Allocate memory delete ptr; // Free memory *ptr = 20; // Attempt to use a deleted pointer (undefined behavior) std::cout << *ptr << std::endl; return 0;
  • 12. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 12 SHRI SHANKARACHARYA TECHNICAL CAMPUS } Explanation: After deleting ptr, it no longer points to a valid memory location, but it still holds an address. Using or dereferencing *ptr after deletion leads to undefined behaviour. To prevent this, set ptr to nullptr after delete: delete ptr; ptr = nullptr; // Now `ptr` is a null pointer, safer if used by mistake Dynamic Memory Management Using new and delete Dynamic memory management in C++ is achieved using the new and delete operators, which allocate and deallocate memory at runtime, rather than compile-time. This approach is useful for creating data structures like arrays or objects whose size or lifetime may not be known until runtime. 1. new Operator: Allocates memory on the heap and returns a pointer to that memory. 2. delete Operator: Deallocates memory allocated with new. Allocating and Deleting a Single Integer Using new and delete to dynamically manage a single integer. #include <iostream> int main() { int *ptr = new int(25); // Allocate memory for an integer and initialize it to 25 std::cout << "Value: " << *ptr << std::endl; delete ptr; // Deallocate the memory ptr = nullptr; // Set pointer to null to avoid dangling pointer return 0; } Explanation: • new int(25) allocates memory for an integer and initializes it to 25. • delete ptr deallocates the memory. • Setting ptr to nullptr after deletion prevents accidental use of a dangling pointer. Example 2: Dynamic Array Allocation and Deallocation Using new and delete[] to allocate and delete an array dynamically. cpp Copy code #include <iostream>
  • 13. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 13 SHRI SHANKARACHARYA TECHNICAL CAMPUS int main() { int *arr = new int[5]; // Dynamically allocate an array of 5 integers // Initialize array elements for (int i = 0; i < 5; ++i) { arr[i] = i * 2; // Set each element to twice its index } // Output array elements for (int i = 0; i < 5; ++i) { std::cout << "arr[" << i << "] = " << arr[i] << std::endl; } delete[] arr; // Deallocate the array arr = nullptr; // Set pointer to null to avoid dangling pointer return 0; } Explanation: • new int[5] allocates an array of 5 integers. • delete[] arr frees the memory allocated for the array. • Setting arr to nullptr helps prevent accidental access to the deallocated memory. • Null Pointer Assignment: Dereferencing or using a null pointer or a pointer that points to deleted memory can cause runtime errors. Always initialize pointers and set them to nullptr after delete. • Dynamic Memory Management: Use new and delete to manage memory dynamically, but match every new with a delete (and new[] with delete[]) to avoid
  • 14. SOMESH KUMAR DEWANGAN DEPARMENT OF CSE 14 SHRI SHANKARACHARYA TECHNICAL CAMPUS memory leaks. Smart pointers (e.g., std::unique_ptr or std::shared_ptr) can be preferable for automatic memory management.