Pointer in C++

Here are three basic examples of pointers in C++:


1️⃣ Basic Example of Pointer in C++

📌 Explanation: A pointer stores the address of a variable.

#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 << "Value stored in ptr: " << ptr << endl;
    cout << "Value at address stored in ptr: " << *ptr << endl;

    return 0;
}

📝 Output:

Value of num: 10
Address of num: 0x61ff08
Value stored in ptr: 0x61ff08
Value at address stored in ptr: 10

2️⃣ this Pointer Example in C++

📌 Explanation: The this pointer refers to the calling object inside a class.

#include <iostream>
using namespace std;

class Example {
    int num;
public:
    Example(int num) {
        this->num = num;  // Using 'this' pointer to refer to the current object
    }
    void show() {
        cout << "Value of num: " << this->num << endl;
    }
};

int main() {
    Example obj(20);
    obj.show();
    return 0;
}

📝 Output:

Value of num: 20

3️⃣ Null Pointer Example in C++

📌 Explanation: A null pointer is a pointer that does not point to any memory location.

#include <iostream>
using namespace std;

int main() {
    int* ptr = NULL;  // Null pointer

    if (ptr == NULL)
        cout << "Pointer is NULL" << endl;
    else
        cout << "Pointer is not NULL" << endl;

    return 0;
}

📝 Output:

Pointer is NULL

Would you like more variations or explanations? 🚀 

Post a Comment

0 Comments