A pointer that points to nothing should be set to nullptr (C++11):
int* p = nullptr; // safe — not pointing to garbage
if (p == nullptr) {
cout << "Pointer is null" << endl;
}
Warning: Dereferencing a null or uninitialized pointer causes undefined behavior (usually a crash). Always initialize pointers.
Exercise
Create an integer variable, a pointer to it, and use the pointer to double the value. Print the result using both the original variable and the pointer.
Show Solution
#include <iostream>
using namespace std;
int main() {
int num = 15;
int* ptr = #
*ptr = *ptr * 2;
cout << "Via variable: " << num << endl; // 30
cout << "Via pointer: " << *ptr << endl; // 30
return 0;
}
Quiz
What does the & operator do when applied to a variable?
A) Performs bitwise AND
B) Declares a reference
C) Returns the memory address of the variable
D) Dereferences a pointer
Answer
C)&x returns the memory address of variable x.
What does *ptr mean when ptr is a pointer?
A) Multiply by ptr
B) Declare a pointer
C) Access the value at the address ptr holds
D) Get the address of ptr
Answer
C)*ptr is the dereference operator — it gives the value stored at the address ptr points to.
Summary
&variable returns the memory address of a variable.
type* ptr declares a pointer that stores an address.
*ptr dereferences — accesses the value at the stored address.
Always initialize pointers; use nullptr for "no address".