Pointer Arithmetic

In pointer arithmetic, we can apply arithmetic operations such as addition, subtraction, increment, and decrement on the pointer to produce new address.

Let’s say we have a pointer ptr of type int of 4 bytes, if we do ptr + 1, it gives memory address which comes after 4 bytes. Similarly, if we do ptr + 2, it gives address after 8 bytes.

For example:

#include <iostream>
#include <typeinfo>
 
int main(int argc, char const *argv[])
{
    int x{};
    const int *ptr{&x};
 
    std::cout << ptr << '\n';
    std::cout << (ptr + 1) << '\n';
    std::cout << (ptr + 2) << '\n';
 
    return 0;
}

On my machine, it gives output:

0x30cf64f84
0x30cf64f88
0x30cf64f8c

See the distance between these address is 4 bytes.

Similarly, we can also do subtraction on pointer:

#include <iostream>
#include <typeinfo>
 
int main(int argc, char const *argv[])
{
    int x{};
    const int *ptr{&x};
 
    std::cout << ptr << '\n';
    std::cout << (ptr - 1) << '\n';
    std::cout << (ptr - 2) << '\n';
 
    return 0;
}

This gives following results on my machine:

0x30a171f84
0x30a171f80
0x30a171f7c

References

  1. https://www.learncpp.com/cpp-tutorial/pointer-arithmetic-and-subscripting/