Topic 42 of 83
Null & Void Pointers
Overview
A Null pointer points to 'nowhere' safely. A Void pointer is a generic pointer that can point to any data type, bypassing strict type checking.
Syntax
cpp
// Null Pointer
int* ptr = nullptr; // Modern C++ (replaces NULL)
if (ptr != nullptr) { /* safe to dereference */ }
// Void Pointer
int x = 5;
double y = 3.14;
void* genericPtr = &x;
genericPtr = &y;Common Pitfalls
- Dereferencing a nullptr causes a Segmentation Fault (instant crash).
Interview Tips
- Always use `nullptr` instead of `NULL` or `0` in modern C++ because `nullptr` is strongly typed as a pointer, preventing function overload resolution ambiguities.
- You cannot dereference a `void*`. You MUST cast it back to its original type first (e.g., `*static_cast<int*>(genericPtr)`).
Real-World Example
Safe initialization and type-casting a void pointer.
example
cpp
#include <iostream>
using namespace std;
int main() {
int* safePtr = nullptr;
int age = 25;
void* vPtr = &age; // Generic pointer
// Must cast before dereferencing
int* intPtr = static_cast<int*>(vPtr);
cout << "Age: " << *intPtr << endl;
return 0;
}