Skip to main content
Library homepage
 
Loading table of contents menu...
Engineering LibreTexts

2.5: Pointer Arithmatic

  • Page ID
    34650
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Pointer Expressions and Pointer Arithmetic

    A limited set of arithmetic operations can be performed on pointers which are:

    • incremented ( ++ )
    • decremented ( — )
    • an integer may be added to a pointer ( + or += )
    • an integer may be subtracted from a pointer ( – or -= )
    • difference between two pointers (p1-p2)

    (Note: Pointer arithmetic is meaningless unless performed on an array.)

    // C++ program to illustrate Pointer Arithmetic in C++ 
    #include <iostream> 
    using namespace std; 
    
    int main() 
    { 
       //Declare an array 
       int v[3] = {10, 100, 200}; 
    
       //declare pointer variable 
       int *ptr; 
    
       //Assign the address of v[0] to ptr 
       ptr = v; 
    
       for (int i = 0; i < 3; i++) 
       { 
          cout << "Value at ptr = " << ptr << "\n"; 
          cout << "Value at *ptr = " << *ptr << "\n"; 
    
          // Increment pointer ptr by 1 
          ptr++; 
       } 
       
       return 0;
    } 

    Output:

    Value at ptr = 0x7fff9a9e7920

    Value at *ptr = 10

    Value at ptr = 0x7fff9a9e7924

    Value at *ptr = 100

    Value at ptr = 0x7fff9a9e7928

    Value at *ptr = 200

    Adapted from:

    "Pointers in C/C++ with Examples" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY 4.0


    This page titled 2.5: Pointer Arithmatic is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.

    • Was this article helpful?