Menu
Coddy logo textTech

Arithmetic - Operations

Lesson 4 of 14 in Coddy's C++ Pointers course.

++ / --

Incrementing or decrementing a pointer moves it to the next or previous memory location of the same data type. This is very useful when we have an array and we set the pointer to point to the first element, with each increment we move one element to the right

int list[] = {1, 2, 3, 4, 5};
int *ptr = &list[0];
cout << *ptr << " ";
ptr++;
cout << *ptr << " ";
ptr--;
cout << *ptr;
Output:
1 2 1

As you can see when we increment/decrement the pointer we move to the next memory location from the same type, in this case to the next/previous element in the array


+= / -=

Adding or subtracting a larger number than 1, can help us move quicker and more elements at a time

int list[] = {1, 2, 3, 4, 5};
int *ptr = &list[0];
cout << *ptr << " ";
ptr += 4;
cout << *ptr << " ";
ptr -= 2;
cout << *ptr;
Output:
1 5 3

n = p2 - p1

The final useful operation that we can do with pointers is to calculate how many elements there are in between them. We can do that by calculating their difference

int list[] = {1, 2, 3, 4, 5};
int *ptr = &list[0];
int *ptr2 = &list[4];
cout << "Between " << *ptr << " and " << *ptr2
 << " there's " << ptr2-ptr << " elements";
Output:
Between 1 and 5 there's 4 elements

We can use these 3 techniques to perform many useful operations with pointers and solve problems in our regular tasks

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Given the following array of integers:

int numbers[] = {10, 20, 30, 40, 50, 60, 70, 80};
  • Create a pointer ptr1 that points to the first element of the array.
  • Create a pointer ptr2 and assign the value of ptr to it
  • Increment ptr2 to move to the fourth element
  • Create ptr3 and give it the value of ptr2 
  • Decrement ptr3 by 2 positions
  • Calculate and PRINT the number of elements between the first and last elements in the array using pointer subtraction in the following way There are {elements} elements between {first} and {last}

Try it yourself

#include <iostream>

using namespace std;

int main() {
    
    int numbers[] = {10, 20, 30, 40, 50, 60, 70, 80};
    
    // Enter code for ptr1
    
    // Enter code for ptr2
    
    // Enter code for ptr3
    
    // Print out the wanted message
    
    
    
    // DO NOT CHANGE ANYTHING BELOW THIS
    // ---------------------------------

    cout << "*ptr1 -> " << *ptr1 << endl;
    cout << "*ptr2 -> " << *ptr2 << endl;
    cout << "*ptr3 -> " << *ptr3 << endl;
    
    return 0;
}

All lessons in C++ Pointers