Pointer Arithmetic
In C++, pointers can be incremented and decremented using pointer arithmetic. This allows us to navigate through arrays and perform various operations.
Let's start by looking at an example:
TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5 int numbers[] = {1, 2, 3, 4, 5};
6 int* p = numbers; // Pointing to the first element of the array
7
8 cout << "First element of the array: " << *p << endl;
9 p++; // Incrementing the pointer
10 cout << "Second element of the array: " << *p << endl;
11 p--; // Decrementing the pointer
12 cout << "Back to the first element of the array again: " << *p << endl;
13
14 return 0;
15}
In this example, we have an integer array numbers
with elements [1, 2, 3, 4, 5]
. We declare a pointer p
and set it to point to the first element of the array.
By using p++
, we increment the pointer to point to the second element of the array. Similarly, p--
decrements the pointer back to the first element.
Executing the code will result in the following output:
SNIPPET
1First element of the array: 1
2Second element of the array: 2
3Back to the first element of the array again: 1
As you can see, pointer arithmetic allows us to easily navigate through arrays and access different elements based on the current pointer position.
xxxxxxxxxx
15
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int* p = numbers; // Pointing to the first element of the array
cout << "First element of the array: " << *p << endl;
p++; // Incrementing the pointer
cout << "Second element of the array: " << *p << endl;
p--; // Decrementing the pointer
cout << "Back to the first element of the array again: " << *p << endl;
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment