Pointer
Introduction
·
A
variable.
·
Stores
the memory address of another variable.
·
Allows
direct access and manipulation of memory.
·
Widely
used for dynamic memory allocation, array handling, function arguments, and
data structures like linked lists etc.
Syntax
datatype *pointer_name;
- datatype:
Type of data the pointer will point to (e.g., int, float, char).
- *
(asterisk): Denotes that the variable is a pointer.
- pointer_name:
Name of the pointer variable.
Example:
·
int
*ptr; // Pointer to an integer
·
float
*fptr; // Pointer to a float
Address-of Operator (&):
- &variable_name:
Returns the memory address of the variable.
pointer_name
= &variable; // Stores the address of 'variable'
Dereference Operator (*):
- *pointer_name:
Accesses the value stored at the memory address that the pointer holds.
*pointer_name
= value; // Modifies the value at the address
Declaring and
Using Pointers
Example:-
#include <iostream>
using namespace std;
int main() {
int num = 10;
int *ptr = # // Pointer storing address of num
cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num <<
endl;
cout << "Pointer ptr points to: " << ptr <<
endl;
cout << "Value at pointer ptr: " << *ptr <<
endl; // Dereferencing pointer
return 0;
}
Output:
Value of num: 10
Address of num: 0x61ff08
Pointer ptr points to: 0x61ff08
Value at pointer ptr: 10
Advantages of Pointers in C++
- Efficient
Memory Management
–dynamic memory allocation and deallocation.
- Improved
Performance –
Direct memory access improves execution speed.
- Used
in Data Structures
– Essential for linked lists, trees, and graphs.
- Function
Arguments
– call-by-reference, reducing
memory usage.
- Flexibility – Useful for handling arrays
and strings efficiently.
Disadvantages of
Pointers in C++
- Complex
Syntax –
Increases code complexity and debugging difficulty.
- Memory
Leaks –
Improper handling of new and delete can lead to leaks.
- Dangling
Pointers –
Using pointers after freeing memory can cause undefined behaviour.
- Security
Issues – Can
be exploited for hacking (e.g., buffer overflow).
5.
Null Pointer Dereferencing: Accessing
*ptr when ptr is nullptr leads to undefined behaviour.
6
--------------------------------------------------------------------------------------------------------------
0 Comments