Using the ++ operator to traverse an array
 

  • The pointer arithmetic (i.e.: *(p+i) ≡ p[i]) enables C programmers to traverse an array using the post-increment ++ operator

  • I will show you step-by-step have you can do this in the following slides

Using the ++ operator to traverse an array

Consider the following for-loop that sum all the array elements:

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;



     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + B[i];

     }

     printf("sum = %d\n", s);
  }  

Using the ++ operator to traverse an array

We define a reference variable of the suitable data type to point to the array B[ ]:

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;
     int *p;


     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + B[i];

     }

     printf("sum = %d\n", s);
  }  

Using the ++ operator to traverse an array

When p points to array B[ ], the p[i] is an alias for B[i]:

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;
     int *p;

     p = B;
     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + p[i]; // p[i] ≡ B[i]

     }

     printf("sum = %d\n", s);
  }  

Using the ++ operator to traverse an array

We re-write p[i] back to *(p+i):

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;
     int *p;

     p = B;
     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + *(p+i); // *(p+i) ≡ p[i] ≡ B[i]

     }

     printf("sum = %d\n", s);
  }  

Using the ++ operator to traverse an array

Instead of adding i to p, we can increment p in a piecemeal manner:

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;
     int *p;

     p = B;
     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + *p; 
        p = p + 1; // Make p point to the next array element
     }

     printf("sum = %d\n", s);
  }  

Using the ++ operator to traverse an array

Use the post-increment ++ operator to simplify the 2 statements:

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;
     int *p;

     p = B;
     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + *(p++); 

     }

     printf("sum = %d\n", s);
  }  

Using the ++ operator to traverse an array

Because post-increment ++ has higher priority (see click here) we can drop the bracket ( ):

  #include <stdio.h>

  int main(int argc, char *argv[])
  {
     int B[10] = {1, 3, 5, 7, 9, 1, 1, 2, 1, 2};
     int s;
     int *p;

     p = B;
     s = 0;
     for (int i = 0; i < 10; i++)
     {
        s = s + *p++; 

     }

     printf("sum = %d\n", s);
  }