DEV Community


Posted on • Updated on

Pointers arithmetic


The real power of pointers is when you want to sequence through the elements of an array.
Since each element in an array is an address in memory (that the pointer references), the ++ or -- operators can be used to iterate through an array.
Since the pointers by default reference the first value in an array using standard declaration, e.g. *pMyArray = myArray;, dereferencing the pointer can be used to quickly get the first value *pMyArray, and indirection can be used to access any other elements further in the array using the following syntax:

*(pMyArray + 3);
// accesses the fourth element
Enter fullscreen mode Exit fullscreen mode

The same syntax can be used to assign values to an array. The two expressions below achieve the same result of assigning the number 27 to the 12th element of the array:

myArray[11] = 27;
*(pMyArray + 10) = 27;
Enter fullscreen mode Exit fullscreen mode

To set the pointer to a specific element, it can be done using the 'address of' operator when it is assigned, along with the index desired: *pMyArray = myArray[3]; sets the pointer to the fourth element of the array.

An example of iterating through an array using pointers and summing the elements is below, with explanation in the comments.

int arraySum(int myArray[], const int num)
  int sum = 0, *ptr;
  int * const myArrayEnd = myArray + num;

  for (ptr = myArray; ptr < myArrayEnd; ++ptr)
    // dereference the pointer to get the value and add the value to the sum
    sum += *ptr;
  return sum;

int main(void)
  int arraySum(int myArray[], const int n);
  int values[5] = {1, 2, 3, 4, 5};

  // here, we are calling the arraySum function with the values array and pointing it to the last element (5)
  printf("The sum is %i \n", arraySum(values, 5));

  return 0;
Enter fullscreen mode Exit fullscreen mode

Functions that process arrays actually use pointers as arguments, so you have a choice between using array notation and pointer notation for array-processing function -- it is a matter of programmer choice.
Like everything in programming, it is a trade-off. Using array notation makes it more obvious that the function is working with arrays, but pointers are closer to machine language and, with some compilers, leads to more efficient code.

Top comments (2)

marciocg profile image
Márcio Conceịç̣̣ão Goulart

Hi there,

i got an error when compiling:
arraysum.c: In function ‘arraySum’:
arraysum.c:7:46: error: ‘n’ undeclared (first use in this function)
const myArrayEnd = myArray + n;
changing 'n' to 'num' worked. Also, where you wrote "10th element of the array..." You're talking about the 12th element, I guess.

These posts about C are great, thanks for sharing!

mikkel250 profile image

Good catch, thanks! I changed the post so these are correct.