C++ Pointer Initialization

Pointer initialization in C++ means assigning a valid memory address to a pointer variable. Proper initialization prevents undefined behavior and runtime errors.

1. Initializing with Variable Address

A pointer is commonly initialized using the address-of operator (&) to store the address of another variable.

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

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

    cout << "Value of num: " << *ptr << endl;
    return 0;
}

2. Initializing with nullptr

If a pointer is not pointing to any valid memory, it should be initialized with nullptr.

C++
Example: Initializing pointer with nullptr
int *ptr = nullptr;

3. Initializing with Dynamic Memory

Pointers can also be initialized using dynamic memory allocation with the new operator.

C++
Example: Dynamic memory initialization
#include <iostream>
using namespace std;

int main() {
    int *ptr = new int;
    *ptr = 100;

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

    delete ptr;  // Free allocated memory
    return 0;
}

4. Common Mistakes

1. Using an uninitialized pointer. 2. Dereferencing a nullptr. 3. Forgetting to delete dynamically allocated memory. 4. Assigning incorrect data type addresses.

5. Best Practices

1. Always initialize pointers at the time of declaration. 2. Use nullptr for safety. 3. Prefer smart pointers (like unique_ptr, shared_ptr) in modern C++. 4. Free dynamically allocated memory to prevent memory leaks.

Conclusion

Proper pointer initialization is crucial for writing safe and efficient C++ programs. Always ensure pointers reference valid memory before dereferencing.