C++ Pointer Declaration

A pointer in C++ is a variable that stores the memory address of another variable. Pointers allow direct access and manipulation of memory.

1. Pointer Syntax

A pointer is declared using the asterisk (*) symbol.

C++
Syntax of pointer declaration
data_type *pointer_name;

// Example
int *ptr;

2. Pointer Initialization

Pointers are usually initialized with the address of a variable using the address-of operator (&).

C++
Example: Initializing a pointer
#include <iostream>
using namespace std;

int main() {
    int num = 10;
    int *ptr = &num;

    cout << "Address of num: " << &num << endl;
    cout << "Value stored in ptr: " << ptr << endl;

    return 0;
}

3. Dereferencing a Pointer

Dereferencing means accessing the value stored at the address held by the pointer using the * operator.

C++
Example: Dereferencing a pointer
#include <iostream>
using namespace std;

int main() {
    int num = 25;
    int *ptr = &num;

    cout << "Value of num: " << *ptr << endl;

    return 0;
}

4. Null Pointer

A pointer that does not point to any valid memory location is called a null pointer. It can be assigned using nullptr.

C++
Example: Null pointer
int *ptr = nullptr;

5. Important Notes

1. Always initialize pointers before using them. 2. Dereferencing an uninitialized pointer causes undefined behavior. 3. Use nullptr instead of NULL in modern C++. 4. The type of pointer must match the type of the variable it points to.

Conclusion

Pointers are powerful features in C++ that allow direct memory access. Understanding pointer declaration, initialization, and dereferencing is essential for advanced programming.