This tutorial aims to provide an in-depth understanding of pointer arithmetic in C++. You will learn how to perform arithmetic operations on pointers and how to use them effectively in your code.
By the end of this tutorial, you will be able to:
- Understand what pointer arithmetic is
- Know how to use addition and subtraction operations on pointers
- Understand the difference between incrementing a pointer and incrementing the value pointed by a pointer
Prerequisites:
- Basic knowledge of C++ programming
- Understanding of pointers in C++
In C++, we can perform arithmetic operations on pointers. These operations include addition, subtraction, increment, and decrement. However, multiplication and division operations are not allowed on pointers.
Here are some important points about pointer arithmetic:
Let's take a look at some examples:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // pointer p points to the first element of the array
cout << *p << endl; // 10
p++; // increment the pointer
cout << *p << endl; // 20
In this example, we first declare an integer array and a pointer that points to the first element of the array. Then, we increment the pointer using p++
. After incrementing, the pointer p
points to the next element in the array.
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[4]; // pointer p points to the last element of the array
cout << *p << endl; // 50
p--; // decrement the pointer
cout << *p << endl; // 40
In this example, the pointer p
initially points to the last element of the array. After we decrement the pointer using p--
, it points to the previous element in the array.
In this tutorial, we've learned about pointer arithmetic in C++, including how to increment and decrement pointers. Remember, pointer arithmetic can be tricky, so it’s important to understand and practice these concepts.
Next steps for learning could involve diving deeper into pointers in C++, such as understanding the relationship between arrays and pointers, and how to use pointers with functions.
Solutions
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // pointer p points to the first element of the array
for(int i = 0; i < 5; i++)
{
cout << *p << endl;
p++; // move the pointer to next element
}
Here, we're moving the pointer p
through the array using the increment operation and printing each element.
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[4]; // pointer p points to the last element of the array
for(int i = 4; i >= 0; i--)
{
cout << *p << endl;
p--; // move the pointer to previous element
}
In this solution, we're moving the pointer p
backwards through the array using the decrement operation and printing each element.
Remember to practice these exercises on your own to reinforce your understanding of pointer arithmetic in C++.