Using pointer arithmetic to access elements in an array

  • Previously:   if we set p to the base address of the array a:

       p = a = &a[0];  // p is the base address of array a

    then the expression:

       p + k   =   &a[k] 


  • Therefore, the expression:   *(p + k) is an alias for a[k]

       *(p + k)   =   *(&a[k])   =  a[k]
           ^              ^
           |              |
       Var at addr    Var at addr
       p + k          of a[k] (Var at "addr of x" is the var x!)
     

  • We have an alternate way to access elements in an array using a reference variable with pointer arithmetic

Using pointer arithmetic to access elements in an array   - Example

  • Example C program:

    int main(int argc, char *argv[])
    {
        int a[10] = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 777 };
        int* p;
    
        p = &a[0];            // p points to variable a[0]
    
        printf("*(p + 0) = %d, a[0] = %d\n", *(p+0), a[0] );
        printf("*(p + 1) = %d, a[1] = %d\n", *(p+1), a[1] );
        printf("*(p + 2) = %d, a[2] = %d\n", *(p+2), a[2] );
        printf("*(p + 3) = %d, a[3] = %d\n", *(p+3), a[3] );
    }  

    Output:

      *(p + 0) = 11, a[0] = 11  // I.e.:  *(p + k) is 
      *(p + 1) = 22, a[1] = 22  // an alias for a[k] !!
      *(p + 2) = 33, a[2] = 33
      *(p + 3) = 44, a[3] = 44    

DEMO: demo/C/set2/pointer-arithm2.c

Comment: pointer arithmetic is more flexible than an ordinary array access expression

  • Previously:

     Suppose we have an array:
    
            int a[10];
    
     If we initialize a reference variable p with a (or &a[0]):
    
            int  *p = a (or &a[0]);  // a[0]a
    
     Then the expression:
    
            p + k = &a[k] (= address of the array element a[k])  
    )


  • Pointer arithmetic provides a more flexible way to access an array

  • Example:   suppose we initialize p to &a[1]....

      • What is the expression p + k equal to ????

Comment: pointer arithmetic is more flexible than an ordinary array access expression

  • After setting p = &a[1]:

      p       ≡ &a[1]   =   &a[0] + sizeof(int)*1
    
      p + 1   ≡  p + sizeof(int)*1
              ≡ (&a[0] + sizeof(int)*1) + sizeof(int)*1
    	  ≡  &a[0] + sizeof(int)*1  + sizeof(int)*1
    	  ≡  &a[0] + sizeof(int)*2&a[2]
    
      p + k   ≡  p + sizeof(int)*k
              ≡ (&a[0] + sizeof(int)*1) + sizeof(int)*k
    	  ≡  &a[0] + sizeof(int)*1  + sizeof(int)*k
    	  ≡  &a[0] + sizeof(int)*(k+1)&a[k+1]
      

  • Therefore, if we initialize p to &a[1], we will get:

      p + k&a[k+1] 

Use: demo/C/set2/pointer-arithm2.c to demonstrate flexibility