Pointers and Memory Management in C++

By Shakib Ansari | Date: Sun, Jun 1, 2025

Agar aap C++ seekh rahe ho, toh pointers ek important aur powerful concept hai. Ye aapko memory ke saath directly kaam karne ki power dete hain. Lekin shuru mein thoda confusing lag sakta hai. Is blog mein hum sab kuch step by step Hinglish mein samjhenge.

1. What is a Pointer?

Pointer ek variable hota hai jo kisi doosre variable ke address ko store karta hai.

Basic Syntax:

int a = 10;
int* ptr = &a;  // 'ptr' holds address of 'a'

Output Example:

cout << "Value of a: " << a << endl;
cout << "Address of a: " << &a << endl;
cout << "Pointer ptr: " << ptr << endl;
cout << "Value at ptr: " << *ptr << endl;

*ptr ka matlab hai value at the address stored in ptr.

2. Pointer Arithmetic

Pointer arithmetic ka matlab hai pointer ke address mein mathematical operations karna (sirf certain operations allowed hain).

Example:

int arr[3] = {10, 20, 30};
int* p = arr;

cout << *p << endl;       // 10
cout << *(p + 1) << endl; // 20
⚠️ Important: p + 1 agle integer location pe chala jata hai, based on datatype size.

3. Dynamic Memory: new and delete

Static memory mein size fixed hota hai. Lekin dynamic memory mein aap runtime pe memory allocate kar sakte ho using new.

Example: Using new

int* p = new int;   // dynamic memory allocation
*p = 100;

cout << *p << endl; // 100

delete p;           // free the memory
Jab memory ka kaam ho jaye, toh hamesha delete karna chahiye. Nahin toh memory leak ho sakta hai.

Array Example:

int* arr = new int[5];   // dynamic array of size 5

for (int i = 0; i < 5; i++) {
    arr[i] = i + 1;
}

for (int i = 0; i < 5; i++) {
    cout << arr[i] << " ";
}

delete[] arr;  // use delete[] for arrays

4. Pointer to Pointer (Double Pointer)

Ek pointer agar kisi doosre pointer ka address store kare, use hum pointer to pointer kehte hain.

Example:

int a = 10;
int* p = &a;
int** q = &p;

cout << "Value of a: " << a << endl;
cout << "Value using *p: " << *p << endl;
cout << "Value using **q: " << **q << endl;

**q basically *(*q) hai, jo a ki value return karega.

5. Pointers with Arrays

Array ka naam khud ek pointer hota hai jo first element ke address ko point karta hai.

Example:

int arr[4] = {10, 20, 30, 40};
int* p = arr;

cout << *p << endl;       // 10
cout << *(p + 2) << endl; // 30
arr[2] ka matlab hai *(arr + 2) – dono same cheez hain.

6. Pointers with Functions

Function Argument as Pointer (Pass by Reference)

#include<iostream>
using namespace std;
void update(int* x) {
    *x = *x + 5;
}

int main() {
    int a = 10;
    update(&a);
    cout << "Updated a: " << a << endl;  // Output: 15
    return 0;
}
Jab aap pointer pass karte ho, toh function original variable pe kaam karta hai.
About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments