Ugenz Academy/Tutorial

Pointers

20 min read3,880 words

Reading progress

Keep learning

C++ Pointers

1. Introduction

A pointer is a variable that stores the memory address of another variable.

In C++, pointers are important for:

  • Working with memory
  • Accessing variables through their addresses
  • Passing data to functions
  • Working with arrays
  • Dynamic memory allocation
  • Building data structures such as linked lists and trees
  • Understanding how memory works

Simple Example

#include <iostream> using namespace std; int main() { int number = 10; int* ptr = &number; cout << "Value = " << number << endl; cout << "Address = " << &number << endl; cout << "Pointer stores = " << ptr << endl; cout << "Value through pointer = " << *ptr << endl; return 0; }

Example Output

The memory address will be different on different computers/runs.

Value = 10 Address = 0x7ffe1234 Pointer stores = 0x7ffe1234 Value through pointer = 10

2. What is a Pointer?

A pointer is a variable that stores the address of another object or variable.

For example:

int number = 10; int* ptr = &number;

Here:

  • number stores 10
  • &number gives the address of number
  • ptr stores that address
  • *ptr accesses the value stored at that address

Representation

number +-----+ | 10 | +-----+ ↑ | ptr stores address

3. Address of a Variable

Every object stored in memory has an address.

The address-of operator & is used to obtain the address of a variable.

Example

#include <iostream> using namespace std; int main() { int number = 25; cout << "Value: " << number << endl; cout << "Address: " << &number; return 0; }

Output

The address varies:

Value: 25 Address: 0x7ff...

4. Pointer Declaration

The basic syntax is:

data_type* pointer_name;

Examples

int* ptr; float* fptr; char* cptr; double* dptr;

The pointer type indicates what type of object the pointer is intended to point to.

5. Initializing a Pointer

A pointer can be initialized with the address of a compatible object.

Example

int number = 50; int* ptr = &number;

Here:

number → 50 ptr → address of number

6. Dereferencing a Pointer

The * operator is called the dereference operator when used with a pointer expression.

It accesses the object referred to by the pointer.

Example

#include <iostream> using namespace std; int main() { int number = 50; int* ptr = &number; cout << *ptr; return 0; }

Output

50

Because:

*ptr

means the value of the object pointed to by ptr.

7. Address-of vs Dereference Operator

The & and * operators have different purposes.

OperatorPurpose
&Gets the address of an object
*Dereferences a pointer to access the pointed-to object

Example

int number = 10; int* ptr = &number;

Here:

&number → address of number ptr → stores the address *ptr → value of number

8. Complete Pointer Example

#include <iostream> using namespace std; int main() { int number = 100; int* ptr = &number; cout << "Number = " << number << endl; cout << "Address of number = " << &number << endl; cout << "Pointer value = " << ptr << endl; cout << "Value using pointer = " << *ptr << endl; return 0; }

Output

The address is system-dependent.

Number = 100 Address of number = 0x7ff... Pointer value = 0x7ff... Value using pointer = 100

9. Changing a Value Using a Pointer

A pointer can be used to modify the object it points to.

Example

#include <iostream> using namespace std; int main() { int number = 10; int* ptr = &number; *ptr = 100; cout << number; return 0; }

Output

100

The statement:

*ptr = 100;

changes the value of number.

10. Pointer and Memory

Consider:

int number = 10; int* ptr = &number;

Conceptually:

Memory Address Value +----------+ +------+ | 0x1000 | ----> | 10 | +----------+ +------+ ↑ | ptr

The actual address will depend on the system and execution.

11. Null Pointer

A null pointer does not point to an object.

Modern C++ uses nullptr to represent a null pointer.

Example

#include <iostream> using namespace std; int main() { int* ptr = nullptr; if (ptr == nullptr) { cout << "Pointer is null"; } return 0; }

Output

Pointer is null

12. Why Use nullptr?

nullptr is the recommended null pointer value in modern C++.

Use:

int* ptr = nullptr;

instead of:

int* ptr = 0;

or the older:

int* ptr = NULL;

nullptr has a dedicated type and avoids some ambiguities associated with integer 0.

13. Uninitialized Pointer

An uninitialized pointer contains an indeterminate value.

Example:

int* ptr;

Do not dereference it.

Incorrect:

cout << *ptr;

This can result in undefined behavior.

Better

int* ptr = nullptr;

14. Pointer to Different Data Types

Pointers can point to different data types.

Integer Pointer

int number = 10; int* ptr = &number;

Float Pointer

float value = 10.5; float* ptr = &value;

Character Pointer

char grade = 'A'; char* ptr = &grade;

The pointer type should be compatible with the object it points to.

15. Pointer Size

The size of a pointer depends on the platform and architecture, not simply on the type of object it points to.

For example:

#include <iostream> using namespace std; int main() { int* p1; double* p2; char* p3; cout << sizeof(p1) << endl; cout << sizeof(p2) << endl; cout << sizeof(p3) << endl; return 0; }

On many 64-bit systems, each may be 8 bytes, but this is platform-dependent.

16. Pointer to Pointer

A pointer can store the address of another pointer.

This is called a pointer to pointer.

Syntax

data_type** pointer_name;

Example

#include <iostream> using namespace std; int main() { int number = 10; int* ptr = &number; int** ptr2 = &ptr; cout << number << endl; cout << *ptr << endl; cout << **ptr2 << endl; return 0; }

Output

10 10 10

Representation

number ↑ ptr ↑ ptr2

17. Pointer to Pointer Example

int number = 50; int* ptr = &number; int** ptr2 = &ptr;

Then:

number → 50 ptr → address of number ptr2 → address of ptr

Therefore:

number

and:

*ptr

and:

**ptr2

all access the value 50.

18. Pointers and Arrays

The name of a built-in array can be used in many expressions as a pointer to its first element.

Example

#include <iostream> using namespace std; int main() { int numbers[3] = {10, 20, 30}; int* ptr = numbers; cout << *ptr << endl; return 0; }

Output

10

Here:

ptr = numbers;

makes ptr point to the first element.

19. Accessing Array Elements Using a Pointer

Example

#include <iostream> using namespace std; int main() { int numbers[5] = {10, 20, 30, 40, 50}; int* ptr = numbers; for (int i = 0; i < 5; i++) { cout << *(ptr + i) << " "; } return 0; }

Output

10 20 30 40 50

Here:

*(ptr + i)

accesses the element at index i.

20. Pointer Arithmetic

Pointer arithmetic allows us to move between elements of an array.

Suppose:

int numbers[3] = {10, 20, 30}; int* ptr = numbers;

Then:

*ptr → 10 *(ptr + 1) → 20 *(ptr + 2) → 30

The pointer advances according to the size of its pointed-to type.

21. Incrementing a Pointer

A pointer can be incremented.

Example

#include <iostream> using namespace std; int main() { int numbers[3] = {10, 20, 30}; int* ptr = numbers; cout << *ptr << endl; ptr++; cout << *ptr << endl; ptr++; cout << *ptr << endl; return 0; }

Output

10 20 30

22. Decrementing a Pointer

A pointer can also be decremented.

Example

#include <iostream> using namespace std; int main() { int numbers[3] = {10, 20, 30}; int* ptr = &numbers[2]; cout << *ptr << endl; ptr--; cout << *ptr << endl; return 0; }

Output

30 20

Pointer arithmetic is valid only within the same array object (or one position past its end, with restrictions on dereferencing).

23. Pointers and Functions

Pointers can be passed to functions.

This allows a function to modify the original object.

Example

#include <iostream> using namespace std; void change(int* ptr) { *ptr = 100; } int main() { int number = 10; change(&number); cout << number; return 0; }

Output

100

24. Swapping Two Values Using Pointers

Pointers can be used to swap two variables.

Example

#include <iostream> using namespace std; void swapNumbers(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } int main() { int x = 10; int y = 20; cout << "Before swapping:" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; swapNumbers(&x, &y); cout << "\nAfter swapping:" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; return 0; }

Output

Before swapping: x = 10 y = 20 After swapping: x = 20 y = 10

25. Pointer to a Function

A pointer can store the address of a function.

Example

#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int main() { int (*operation)(int, int) = add; cout << operation(10, 20); return 0; }

Output

30

Function pointers are useful when a program needs to select or pass a function dynamically.

26. Dynamic Memory Allocation

Dynamic memory allocation means obtaining memory during program execution.

C++ provides:

new delete

for manual dynamic memory management.

Example

#include <iostream> using namespace std; int main() { int* ptr = new int; *ptr = 50; cout << *ptr; delete ptr; ptr = nullptr; return 0; }

Output

50

27. Dynamic Array

A dynamically allocated array can be created using new[].

Example

#include <iostream> using namespace std; int main() { int size; cout << "Enter array size: "; cin >> size; int* numbers = new int[size]; for (int i = 0; i < size; i++) { numbers[i] = i + 1; } cout << "Array: "; for (int i = 0; i < size; i++) { cout << numbers[i] << " "; } delete[] numbers; numbers = nullptr; return 0; }

Example Input

5

Output

Array: 1 2 3 4 5

28. new and delete

new

The new operator dynamically allocates an object.

int* ptr = new int;

delete

The delete operator releases memory allocated for one object.

delete ptr;

For an array allocated with new[], use:

delete[] ptr;

Important

new → delete new[] → delete[]

Do not mix them.

29. Memory Leak

A memory leak happens when dynamically allocated memory is no longer needed but is not released.

Example:

int* ptr = new int(10); // Forgot to delete ptr

The allocated memory remains unavailable for reuse until the program or appropriate memory-management mechanism releases it.

Correct

int* ptr = new int(10); delete ptr; ptr = nullptr;

In modern C++, prefer RAII and standard library containers/smart pointers instead of raw new/delete where possible.

30. Dangling Pointer

A dangling pointer is a pointer that refers to an object whose lifetime has ended or to memory that is no longer valid for access.

Example:

int* ptr = new int(10); delete ptr;

After delete, ptr should not be dereferenced.

Better:

delete ptr; ptr = nullptr;

31. Smart Pointers

Modern C++ provides smart pointers to help manage dynamically allocated objects automatically.

Important smart pointers include:

  • std::unique_ptr
  • std::shared_ptr
  • std::weak_ptr

They are available through the <memory> header.

32. unique_ptr

A unique_ptr represents exclusive ownership of an object.

Example

#include <iostream> #include <memory> using namespace std; int main() { unique_ptr<int> ptr = make_unique<int>(100); cout << *ptr; return 0; }

Output

100

When ptr goes out of scope, the object is automatically destroyed.

33. shared_ptr

A shared_ptr allows multiple smart pointers to share ownership of an object.

Example

#include <iostream> #include <memory> using namespace std; int main() { shared_ptr<int> p1 = make_shared<int>(100); shared_ptr<int> p2 = p1; cout << *p1 << endl; cout << *p2 << endl; cout << "Owners: " << p1.use_count(); return 0; }

Output

100 100 Owners: 2

The object is automatically destroyed when the last owning shared_ptr is destroyed.

34. weak_ptr

A weak_ptr observes an object managed by shared_ptr without owning it.

It is especially useful for avoiding ownership cycles.

Example

#include <iostream> #include <memory> using namespace std; int main() { shared_ptr<int> shared = make_shared<int>(50); weak_ptr<int> weak = shared; if (!weak.expired()) { cout << "Object is still available"; } return 0; }

Output

Object is still available

A weak_ptr must be converted to a temporary shared_ptr using .lock() before safely accessing the object.

35. Pointer to a Constant

A pointer can point to a constant object.

Example

const int number = 10; const int* ptr = &number;

Through ptr, we cannot modify number.

Incorrect:

*ptr = 20;

36. Constant Pointer

A constant pointer cannot be changed to point to another object after initialization.

Example

int a = 10; int b = 20; int* const ptr = &a;

This is not allowed:

ptr = &b;

But this is allowed:

*ptr = 100;

The pointer itself is constant, but the pointed-to object is not.

37. Constant Pointer to Constant Data

Both the pointer and the pointed-to data cannot be changed through that pointer.

Example

int a = 10; const int* const ptr = &a;

Through ptr:

  • The pointed-to value cannot be modified.
  • The pointer cannot point somewhere else.

38. Pointer vs Reference

Pointers and references both allow indirect access to objects, but they are different.

PointerReference
Stores an addressActs as another name for an object
Can be nullptrNormally must refer to an object
Can be changed to point elsewhereCannot be reseated after initialization
Uses * to dereferenceUsually used directly
Supports pointer arithmetic in appropriate casesDoes not support pointer arithmetic
Example: int* pExample: int& r

Example

int number = 10; int* ptr = &number; int& ref = number;

39. Pointer to Structure

Pointers can point to structures.

Example

#include <iostream> using namespace std; struct Student { int age; }; int main() { Student student = {20}; Student* ptr = &student; cout << ptr->age; return 0; }

Output

20

The -> operator is commonly used to access members through a pointer to an object.

40. . vs ->

For a normal object:

student.age

For a pointer to the object:

ptr->age

Example

Student student; Student* ptr = &student;

Then:

student.age

and:

ptr->age

refer to the same member.

41. Pointers with Strings

A pointer can point to a character in a character array.

Example

#include <iostream> using namespace std; int main() { char name[] = "Anu"; char* ptr = name; cout << ptr; return 0; }

Output

Anu

For ordinary modern C++ text processing, std::string is generally preferred over raw character pointers.

42. void* Pointer

A void* is a pointer to an object of an unspecified type.

Example

#include <iostream> using namespace std; int main() { int number = 10; void* ptr = &number; cout << *static_cast<int*>(ptr); return 0; }

Output

10

A void* must be converted to an appropriate pointer type before dereferencing.

43. Pointer Safety

When working with pointers, remember:

1. Initialize pointers

Prefer:

int* ptr = nullptr;

rather than leaving a pointer uninitialized.

2. Do not dereference null pointers

Incorrect:

int* ptr = nullptr; cout << *ptr;

3. Do not dereference dangling pointers

After:

delete ptr;

do not use:

*ptr

4. Avoid memory leaks

Release manually allocated memory or, preferably, use RAII and smart pointers.

5. Stay within array bounds

Do not use pointer arithmetic to access outside the valid array object.

44. Complete Pointer Program

The following program demonstrates addresses, pointers, dereferencing, and changing a value.

#include <iostream> using namespace std; int main() { int number = 25; int* ptr = &number; cout << "Original value: " << number << endl; cout << "Address of number: " << &number << endl; cout << "Pointer contains: " << ptr << endl; cout << "Value using pointer: " << *ptr << endl; *ptr = 100; cout << "New value: " << number << endl; return 0; }

Output

The address will vary:

Original value: 25 Address of number: 0x7ff... Pointer contains: 0x7ff... Value using pointer: 25 New value: 100

45. Complete Pointer and Array Program

#include <iostream> using namespace std; int main() { int numbers[5] = {10, 20, 30, 40, 50}; int* ptr = numbers; cout << "Array elements using pointer:" << endl; for (int i = 0; i < 5; i++) { cout << *(ptr + i) << " "; } return 0; }

Output

Array elements using pointer: 10 20 30 40 50

46. Complete Pointer and Function Program

#include <iostream> using namespace std; void doubleValue(int* ptr) { *ptr = *ptr * 2; } int main() { int number = 25; cout << "Before: " << number << endl; doubleValue(&number); cout << "After: " << number << endl; return 0; }

Output

Before: 25 After: 50

47. Common Pointer Errors

Error 1: Dereferencing a Null Pointer

Incorrect:

int* ptr = nullptr; cout << *ptr;

A null pointer does not point to an object that can be accessed.

Error 2: Using an Uninitialized Pointer

Incorrect:

int* ptr; *ptr = 10;

The pointer does not have a valid target.

Error 3: Using a Pointer After delete

Incorrect:

int* ptr = new int(10); delete ptr; cout << *ptr;

After delete, the object no longer exists.

Error 4: Incorrect Array Bounds

int numbers[5] = {1, 2, 3, 4, 5}; int* ptr = numbers; cout << *(ptr + 5);

The valid element positions are 0 through 4. Dereferencing ptr + 5 is invalid.

48. Advantages of Pointers

  • Allow indirect access to objects.
  • Useful for passing objects to functions.
  • Useful for modifying original values.
  • Useful for array processing.
  • Support dynamic memory management.
  • Useful for implementing data structures.
  • Useful for low-level and systems programming.
  • Function pointers support flexible function selection.
  • Smart pointers provide automatic resource management.

49. Disadvantages of Pointers

  • Incorrect use can cause undefined behavior.
  • Null pointer dereferencing can crash a program.
  • Dangling pointers can cause serious errors.
  • Manual dynamic memory management can cause memory leaks.
  • Pointer arithmetic can be difficult for beginners.
  • Incorrect pointer types or casts can cause bugs.
  • Raw pointers do not automatically manage ownership.

50. Important Pointer Operators

OperatorNamePurpose
&Address-ofGets the address of an object
*DereferenceAccesses the pointed-to object
->Arrow operatorAccesses members through an object pointer
++IncrementMoves a pointer to the next array element in appropriate contexts
--DecrementMoves a pointer to the previous array element in appropriate contexts

51. Pointer Summary

ConceptExample
Pointer declarationint* ptr;
Address&number
Dereference*ptr
Null pointernullptr
Pointer to pointerint** ptr;
Array pointerint* ptr = numbers;
Pointer arithmeticptr + 1
Function pointerint (*ptr)(int, int)
Dynamic allocationnew
Release one objectdelete
Release arraydelete[]
Smart pointerunique_ptr<int>
Shared ownershipshared_ptr<int>
Non-owning observerweak_ptr<int>

52. Pointer Concept Diagram

POINTER | +------------+------------+ | | | Address Value Memory | | | ↓ ↓ ↓ &variable *pointer new/delete | ↓ Pointer | +-----+------+ | | Array Function | | ↓ ↓ ptr + i Function Pointer

53. Key Points to Remember

  1. A pointer stores the address of an object.
  2. & obtains an address.
  3. * dereferences a pointer.
  4. Use nullptr for a pointer that points to no object.
  5. Never dereference a null or invalid pointer.
  6. Initialize pointers before using them.
  7. Pointer arithmetic is commonly used with arrays.
  8. Arrays and pointers are closely related but are not the same thing.
  9. Pointers can be passed to functions.
  10. new dynamically allocates objects.
  11. delete releases an object allocated with new.
  12. delete[] releases an array allocated with new[].
  13. Modern C++ generally prefers RAII, containers, and smart pointers over manual memory management.
  14. unique_ptr, shared_ptr, and weak_ptr are important smart-pointer types.
  15. Pointers are powerful but must be used carefully.

54. Conclusion

Pointers are one of the most important and powerful concepts in C++. A pointer stores the memory address of an object and allows a program to access or modify that object indirectly.

The most important concepts are:

Pointer ↓ Address (&) ↓ Pointer Variable ↓ Dereference (*) ↓ Arrays ↓ Functions ↓ Dynamic Memory ↓ Smart Pointers

A strong understanding of pointers provides a foundation for advanced C++ topics such as dynamic data structures, linked lists, trees, memory management, object-oriented programming, and low-level programming.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy