Back to C++
2026-03-087 min read

Changing Value Pointed by Pointers (C++)

Learn Changing Value Pointed by Pointers (C++) step by step with clear examples and exercises.

Why This Matters

Understanding how to change values pointed by pointers is crucial in C++ programming. This skill allows you to manipulate memory directly, write efficient code, and solve complex problems. Mastering pointer manipulation can help you debug real-world issues and create more robust programs.

Prerequisites

Before diving into the core concept, it is important that you have a solid understanding of the following topics:

  1. C++ Basics: Variables, Data Types, Operators, and Control Structures
  2. Pointers Introduction: Understanding what pointers are, how they work, and basic pointer operations
  3. Memory Allocation: new, delete, and dynamic memory management
  4. Basic Input/Output Operations: Using cin and cout to read from and write to the console
  5. Control Structures: Loops (for, while, and do-while) and conditional statements (if, else, and switch)
  6. Functions: Defining, calling, and passing arguments to functions
  7. Arrays: Understanding how arrays work and accessing their elements using subscripts
  8. Understanding the difference between stack and heap memory
  9. Understanding the concept of null pointers (nullptr or 0)

Core Concept

A pointer is a variable that stores the memory address of another variable. To change the value pointed by a pointer, you need to use the dereference operator (*) to access the memory location and assign a new value.

int num = 10;
int *ptr = # // ptr points to num
*ptr = 20; // change the value of num through ptr

In this example, we create an integer variable num and a pointer ptr that points to num. We then assign the new value 20 to the memory location pointed by ptr, which changes the value of num.

Dereferencing Pointers

To access the value stored at the memory address pointed by a pointer, you can use the dereference operator (*) before the pointer.

int num = 10;
int *ptr = # // ptr points to num
cout << *ptr; // prints 10 (the value of num)

Pointer Arithmetic

You can perform arithmetic operations on pointers to move them to adjacent memory locations. This is known as pointer arithmetic.

int arr[3] = {1, 2, 3};
int *ptr = arr; // ptr points to the first element of arr
ptr++; // moves ptr to the next memory location (the second element)
cout << *ptr; // prints 2 (the value of the second element)

Pointer Arithmetic with Arrays

When dealing with arrays, it's important to understand that array names are implicitly converted to pointers to their first elements. This means that you can use pointer arithmetic directly on array names.

int arr[3] = {1, 2, 3};
cout << arr[0]; // prints 1 (the value of the first element)
cout << *(arr + 1); // also prints 1 (since arr + 1 points to the second element)

Pointer Increment and Decrement

In addition to using ptr++ and ptr--, you can also use the increment (++) and decrement (--) operators directly on pointers.

int arr[3] = {1, 2, 3};
int *ptr = arr; // ptr points to the first element of arr
++ptr; // moves ptr to the next memory location (the second element)
cout << *ptr; // prints 2 (the value of the second element)

Common Mistakes

  1. Forgetting to initialize pointers: Always initialize your pointers to nullptr or a known value before using them.
  2. Not understanding pointer arithmetic: Be careful when moving pointers, as incorrect pointer arithmetic can lead to out-of-bounds memory access and potential crashes.
  3. Using pointers inappropriately: Avoid using pointers when simpler solutions are available or when the complexity of your code increases unnecessarily.
  4. Failing to free dynamically allocated memory: Always deallocate memory you've allocated with new to avoid memory leaks.
  5. Not checking for null pointers before dereferencing: Always check if a pointer is not null before dereferencing it to prevent undefined behavior and potential crashes.
  6. Incorrectly using the address-of operator (&) or dereference operator (*): Ensure you are using these operators correctly, as incorrect usage can lead to errors.
  7. Confusing pointers with references: While both pointers and references allow you to access variables indirectly, they behave differently in certain contexts. Make sure you understand the differences between them.
  8. Not understanding the difference between stack and heap memory: Understanding where your variables are stored can help you avoid common pitfalls when using pointers.
  9. Incorrectly handling array bounds: Be aware of array bounds, as accessing elements outside the valid range can lead to undefined behavior and potential crashes.
  10. Not properly managing dynamic memory allocation: Ensure that you allocate enough memory for your needs and deallocate it when it's no longer needed to avoid memory leaks.

Worked Example

Let's create a simple program that takes user input, stores it in an array using pointers, and then calculates the sum of the elements.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;

int *arr = new int[n]; // dynamically allocate memory for an array of size n

cout << "Enter " << n << " integers: ";
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}

int sum = 0;
int *ptr = arr; // ptr points to the first element of arr
while (ptr != arr + n) {
sum += *ptr; // add the current value to the sum
ptr++; // move to the next memory location
}

cout << "The sum of the elements is: " << sum << endl;

delete[] arr; // free the dynamically allocated memory
return 0;
}

Practice Questions

  1. Write a program that sorts an array of integers using pointers and bubble sort algorithm.
  2. Given two strings, write a function that checks if they are anagrams using pointers.
  3. Implement a function that reverses the elements in an array using pointers.
  4. Create a program that finds the second largest number in an array using pointers.
  5. Write a function that takes a pointer to an integer and increments its value by a given amount.
  6. Implement a stack data structure using pointers.
  7. Write a program that implements a simple calculator using pointers for handling operands and operators.
  8. Given two arrays, write a function that compares them using pointers and returns true if they are equal and false otherwise.
  9. Write a function that finds the maximum number in an array using pointers.
  10. Implement a linked list data structure using pointers.

FAQ

What happens when we assign a pointer to another pointer?

When you assign a pointer to another pointer, you create a new pointer variable that points to the same memory address as the original pointer. This is often used for functions that return pointers or for passing pointers as function arguments.

Can I use pointers with built-in data types like int and char?

Yes, you can use pointers with all data types in C++, including built-in ones like int and char.

How do I check if a pointer is null or not?

To check if a pointer is null (or points to an invalid memory address), you can compare it to nullptr or 0. However, it's generally better to initialize your pointers to a known value before using them to avoid errors.

How do I swap the values of two variables using pointers?

You can swap the values of two variables using pointers by creating a temporary variable and swapping the addresses stored in the pointers.

int a = 5, b = 10;
int temp;
int *pa = &a, *pb = &b;
temp = *pa;
*pa = *pb;
*pb = temp;

What is the difference between a pointer and a reference?

A pointer is a variable that stores the memory address of another variable, while a reference is an alias for another variable. References are typically more convenient for function arguments, as they eliminate the need for dereferencing. However, pointers offer more flexibility in certain situations, such as when dealing with dynamic memory allocation or complex data structures.

What happens if I delete a pointer that was not allocated using new?

Deleting a pointer that was not allocated using new can lead to undefined behavior and potential crashes, as the program tries to free memory that it does not own. Always ensure you are deallocating memory correctly to avoid these issues.

What is the difference between stack and heap memory?

Stack memory is a region of memory used for local variables and function call frames, while heap memory is a region of memory used for dynamically allocated objects (using new). Stack memory is automatically managed by the compiler, while heap memory must be manually managed using new and delete.

How do I properly manage dynamic memory allocation?

To properly manage dynamic memory allocation, always allocate enough memory for your needs and deallocate it when it's no longer needed to avoid memory leaks. Be aware of array bounds, as accessing elements outside the valid range can lead to undefined behavior and potential crashes.

What are some common pitfalls when using pointers?

Some common pitfalls when using pointers include forgetting to initialize them, not understanding pointer arithmetic, using pointers inappropriately, failing to free dynamically allocated memory, not checking for null pointers before dereferencing, incorrectly handling array bounds, and not properly managing dynamic memory allocation.

How do I handle errors when using pointers?

To handle errors when using pointers, always check if a pointer is not null before dereferencing it to prevent undefined behavior and potential crashes. Use good programming practices such as initializing your pointers, checking for array bounds, and properly managing dynamic memory allocation to minimize errors.

Changing Value Pointed by Pointers (C++) | C++ | XQA Learn