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 1As 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 3n = 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 elementsWe can use these 3 techniques to perform many useful operations with pointers and solve problems in our regular tasks
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyGiven the following array of integers:
int numbers[] = {10, 20, 30, 40, 50, 60, 70, 80};- Create a pointer
ptr1that points to the first element of the array. - Create a pointer
ptr2and assign the value ofptrto it - Increment
ptr2to move to the fourth element - Create
ptr3and give it the value ofptr2 - Decrement
ptr3by 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
1Pointer Fundamentals
Introduction to PointersDeclaration & InitializationArithmetic - AssignmentArithmetic - OperationsConst PointersPointers & Arrays2Pointers & References
Pointers as ParametersReferences - &References as ParametersPointers vs References