Pointer in C++

 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 = &num; // 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++

  1. Efficient Memory Management –dynamic memory allocation and deallocation.
  2. Improved Performance – Direct memory access improves execution speed.
  3. Used in Data Structures – Essential for linked lists, trees, and graphs.
  4. Function Arguments –  call-by-reference, reducing memory usage.
  5. Flexibility – Useful for handling arrays and strings efficiently.

 

Disadvantages of Pointers in C++

  1. Complex Syntax – Increases code complexity and debugging difficulty.
  2. Memory Leaks – Improper handling of new and delete can lead to leaks.
  3. Dangling Pointers – Using pointers after freeing memory can cause undefined behaviour.
  4. 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

--------------------------------------------------------------------------------------------------------------

 

Post a Comment

0 Comments